Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't "+" operate on characters in R?

Call me lazy, but I just hate typing things like paste("a","b",sep='') all the time.

I know that "(t)his is R. There is no if, only how." (library(fortunes);(fortune(109)). So, my follow up question is: Is it possible to easily change this behavior?

like image 727
Eduardo Leoni Avatar asked Aug 23 '09 22:08

Eduardo Leoni


People also ask

What does \t do in R?

t() function in R Language is used to calculate transpose of a matrix or Data Frame.

How to write on a new line in R?

Special Characters in Strings The most commonly used are "\t" for TAB, "\n" for new-line, and "\\" for a (single) backslash character.

What is class character in R?

A character object is used to represent string values in R. We convert objects into character values with the as.character() function: > x = as.character(3.14)


2 Answers

@ Dirk: For once, you're not quite right. It's not the parser. One can write methods in R for "+" -- help("+") goes to "Arithmetic operators" and mentions that these are generic and you can write methods for them ... and of course many package writers do, e.g., we do for the 'Matrix' package, and I also do for the "Rmpfr" package, e.g. But Dirk is also right (of course!) that you cannot do it in R currently, by just defining a method for "+.character".

About three years ago, I had started a thread on R-devel (the R mailing list on R development; very much recommended if you are interested in these topics; you can also access through Gmane if you don't want to subscribe) :r-devel archived msg

It came to an interesting discussion with quite a few pros and cons, notably John Chambers ("the father of S and hence R") pretty strongly opposing to use "+" for an operation that is not commutative, and also r-devel archived msg2 (by another R-core member), supporting the view that we (R Core) should not adopt / support the idea; and if people **really* wanted it, they could define %+% for that.

like image 180
Martin Mächler Avatar answered Sep 30 '22 03:09

Martin Mächler


Is using sprintf any more convenient for you?

Barring that, how about this little sleight of hand:

'%+%' <- paste

'and' %+% 'now' %+% 'for'%+% 'something' %+% 'completely' %+% 'different'    
# [1] "and now for something completely different"
like image 43
Steve Lianoglou Avatar answered Sep 30 '22 03:09

Steve Lianoglou