0

The "+" supports numeric, integer and Date in r. All below operations are valid.

> 5 + 5L
[1] 10
> Sys.Date() + 5
[1] "2018-01-18"

But + doesn't work between character. Like:

> "one" + "one"
Error in "one" + "one" : non-numeric argument to binary operator
> "What is date today? Ans:" + Sys.Date()
Error in unclass(e1) + unclass(e2) : 
  non-numeric argument to binary operator

Is it forbidden to allow other than numeric argument in r? Or someone can overwrite + behavior to support other types of argument.

MKR
  • 19,739
  • 4
  • 23
  • 33
  • What do you expect `"one" + "one"` to result in? – Carcigenicate Jan 13 '18 at 19:48
  • @Carcigenicate I was looking for substitute of `paste`. That means, I was expecting `"oneone"`. – MKR Jan 13 '18 at 19:49
  • Why is this behaviour inconsistent? What do you expect `"one"+"two"` to deliver? It just is not defined for character arguments. – Bhas Jan 13 '18 at 19:49
  • 3
    Well just use `paste`. – Bhas Jan 13 '18 at 19:50
  • 1
    @MKR Oh, so string concatenation. R creators seem to have chosen for `+` to he used solely for numeric uses. Doesn't seem inconsistent. – Carcigenicate Jan 13 '18 at 19:51
  • @Bhas Yes. `paste` is available but sometime I miss that capability. esp. while using from command line in `RStudio`. – MKR Jan 13 '18 at 19:52
  • @Carcigenicate Agree. Title of issue is not appropriate. There is no consistency. Rather I'm looking for additional feature. – MKR Jan 13 '18 at 19:53
  • 2
    `\`%+%\` <- function(e1, e2) paste0(e1, e2); "one" %+% "one"` This has been asked before. – Rich Scriven Jan 13 '18 at 20:04
  • @RichScriven Thanks Rich. It seems solution from `aocall` is more elegant. – MKR Jan 13 '18 at 20:07
  • 1
    ... which is also the same as [this answer](https://stackoverflow.com/questions/4730551/making-a-string-concatenation-operator-in-r/30649288#30649288) on that question. – Rich Scriven Jan 13 '18 at 20:09
  • @RichScriven yes. I should have done some more research before asking it. Thanks again. – MKR Jan 13 '18 at 20:11

1 Answers1

7

You could redefine +, though I don't recommend it.

`+` <- function(x, y) UseMethod("+")
`+.character` <- function(x, y) paste0(x, y)
`+.default` <- .Primitive("+")

1 + 1 ##2
"a" + "b" ##"ab"
"a" + 2 ##"a2"
alan ocallaghan
  • 3,116
  • 17
  • 37