0

I'm a big fan of the + operator for string concatenation in Python. I would like to extend/customize the + operator to do the same thing in R.

Here's what I have so far:

`+` <- function(a, b){
    if(is.numeric(a)){
        sum(a, b)
    }else{
        paste0(a, b)
    }

This works pretty well, but in some speed tests, performs poorly compared to the original/primitive +. So, how can I refer to the primitive + instead of sum() in the second line of the function? If I just use +, of course R gives me a node stack overflow from infinite recursion.

Amadou Kone
  • 907
  • 11
  • 21

1 Answers1

1

(The answer offered in the duplicate question is another alternative, cleaner perhaps in that it does not add another function.)

Save the primitive as another function. Here I'll use a "special" function %plus% (so that it can be inlined), but it could be simply plus if you'd prefer.

`%plus%` <- `+`
`+` <- function(e1, e2) if (is.numeric(e1)) `%plus%`(e1, e2) else paste0(e1, e2)
1+2
# [1] 3
'a'+'b'
# [1] "ab"
r2evans
  • 141,215
  • 6
  • 77
  • 149