1

Is there a package that would extend the + operator with method for character types ( i.e. `+.character` <-function(x,y) {...} )?

In base R, writing this yields error:

"a" + "b" # Error in "a" + "b" : non-numeric argument to binary operator 

What I would like to achieve is:

"a" + "b" #"ab" 

I am aware of paste0("a","b"), but "a" + "b" is arguably more readable/shorter.

Of course there is always possibility to define special binary operator:

`%+%` <- function(x,y) paste0(x,y) "foo" %+% "bar" %+% "baz" # "foobarbaz" 
1
  • 2
    character is a special class (it's also a type). It looks like + is hardcoded to give this error for character input and never calls the method in such a case. Commented May 13, 2015 at 11:15

2 Answers 2

1

stringi provides %s+% operator:

> library(stringi) > "a" %s+% "b" [1] "ab" 

and %stri+% operator:

> "a" %stri+% "b" [1] "ab" 
Sign up to request clarification or add additional context in comments.

Comments

0

In order to improve the readability of your code, you may enhance base + function so it would work like in Python:

"+" <- function(x, y) { if(is.character(x) || is.character(y)) { return(paste(x, y, sep = "")) } else { .Primitive("+")(x, y) } } "a" + "b" [1] "ab" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.