Daniel Krizian
Daniel Krizian

Reputation: 4716

Concatenate strings - convenience wrapper?

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"

Upvotes: 1

Views: 141

Answers (2)

George Shimanovsky
George Shimanovsky

Reputation: 1956

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"

Upvotes: 0

zero323
zero323

Reputation: 330063

stringi provides %s+% operator:

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

and %stri+% operator:

> "a" %stri+% "b"
[1] "ab"

Upvotes: 1

Related Questions