Operation overloading in R [duplicate]

ぃ、小莉子 提交于 2019-12-06 03:11:14

问题


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


回答1:


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




回答2:


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




回答3:


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.




回答4:


You can find this operator in stringi package.

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



来源:https://stackoverflow.com/questions/5322546/operation-overloading-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!