# [Rd] "+" operator on characters revisited

Vitalie S. spinuvit.list at gmail.com
Sun Jan 23 21:15:59 CET 2011

```Spencer Graves <spencer.graves at structuremonitoring.com> writes:

> On 1/23/2011 8:50 AM, peter dalgaard wrote:
>> On Jan 22, 2011, at 21:08 , Vitalie S. wrote:
>>
>>> The only definite argument occurred in the thread against "+" operator
>>> was the lack of commutativity (as if one have to prove algebraic
>>> theorems in R).
>> I think the real killer was associativity, combined with coercion rules:
>>
>> Is "x"+1+2 supposed to be equal to "x12" or "x3"?
>>
>       Excellent:  This seems like a good reason to follow Python:  Allow "a+b" with a character vector "a" only if
> "b" is also a character vector (or factor?).
>
>       This example raises another question:  If we allow "a+b" for "a" and "b" both character vectors (and give an
> error if one is numeric), what do we do with factors?  If "a" is a factor,
> return a factor?

If we define custom %+% as:

`%+%` <- function(a, b){
if(is.character(a) || is.character(b))
paste(as.character(a), as.character(b), sep="")
else
a + b
}

because of higher precedence of %any% operators over binary + we have:

"a" %+% 1 %+% 2
## [1] "a12"

and

str("a" %+% factor(1:2))
## chr [1:2] "a1" "a2"

so if + on characters would behave "as if" having slightly higher priority than
other + operators that might solve reasonably the problem.

Vitalie.

```