Operation overloading in R [duplicate]

守給你的承諾、 提交于 2019-12-04 09:16:34

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

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

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.

You can find this operator in stringi package.

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

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