Reputation: 4716
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
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