Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operation overloading in R [duplicate]

What's the most straight forward way of overloading '+' for characters? I have defined '%+%' <- function(...) paste(...,sep=""):

str <- "aa"%+%"bb"%+%"cc" #str="aabbcc"

But I don't like the syntax. I think str <- "aa"+"bb"+"cc" would be nicer.

(I am building long SQL queries to use with RODBC, the usual paste is not very handy in such situations. Any suggestions?)

like image 974
teucer Avatar asked Mar 16 '11 08:03

teucer


3 Answers

You may try something like that :

R> oldplus <- `+`
R> `+` <- function(e1, e2) { 
R>     if (is.character(e1) && is.character(e2)) { 
R>          paste(e1,e2,sep="") 
R>      }
R>      else { 
R>          oldplus(e1,e2) 
R>      } 
R>  }

Which gives :

R> 2+3
[1] 5
R> "aa"+"bb"
[1] "aabb"

But as Sacha pointed out, overloading such a basic function is very dangerous, and I can't assure you it will not break your R session and make your computer explode :-)

like image 169
juba Avatar answered Sep 28 '22 14:09

juba


I think that using two arguments is better than the dots:

'%+%' <- function(x,y) paste(x,y,sep="")

"a"%+%"b"%+%"C"
[1] "abC"

If you really really want to you can overwrite +, but be veeeeery careful when doing this as you will break one of the most important functions in R. I can't think of any reason why you would want to do that over %+%:

# '+' <- function(x,y) paste(x,y,sep="")
# "a"+"b"+"C"
# [1] "abC"

rm('+')

commented it out to be sure I don't accidently break someones R:)

like image 20
Sacha Epskamp Avatar answered Sep 28 '22 16:09

Sacha Epskamp


Why is the usual 'paste' not very handy? It's what it's meant for. Suggestions:

Write yourself an unusual paste function that does what you want. Maybe you just don't like typing 'sep=""' all the time. So write a function that calls paste with sep="". Or whatever.

Building long SQL queries with string concatenation is potential fail anyway. See http://xkcd.com/327/ for the canonical example.

Another possibility is some kind of templating solution. I've used the brew package in the past and it's great for that.

like image 45
Spacedman Avatar answered Sep 28 '22 16:09

Spacedman