Operation overloading in R [duplicate]

2019-04-10 06:17发布

This question already has an answer here:

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?)

4条回答
小情绪 Triste *
2楼-- · 2019-04-10 06:44

You can find this operator in stringi package.

http://docs.rexamine.com/R-man/stringi/oper_plus.html

查看更多
爷、活的狠高调
3楼-- · 2019-04-10 06:46

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 :-)

查看更多
甜甜的少女心
4楼-- · 2019-04-10 06:48

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:)

查看更多
The star\"
5楼-- · 2019-04-10 06:51

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.

查看更多
登录 后发表回答