From spencer.graves at structuremonitoring.com  Sun Jan 23 23:30:01 2011
From: spencer.graves at structuremonitoring.com (Spencer Graves)
Date: Sun, 23 Jan 2011 14:30:01 -0800
Subject: [Rd] "+" operator on characters revisited
In-Reply-To: <87vd1fbclc.fsf@gmail.com>
References: <878vycd7ld.fsf@gmail.com>	<E410A01D-653A-434F-B971-9EAC08324AC8@gmail.com>	<4D3C610F.4000005@structuremonitoring.com>
	<87vd1fbclc.fsf@gmail.com>
Message-ID: <4D3CABE9.6020208@structuremonitoring.com>



On 1/23/2011 12:15 PM, Vitalie S. wrote:
> 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.

No:  'a' %+% (1 %+%2)  != ('a' %+% 1) %+% 2, as Peter Dalgaard noted:  
'a3' != 'a12'.


> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel



[Rd] "+" operator on characters revisited
Spencer Graves