Overloading Ampersand & operator in R

浪尽此生 提交于 2019-12-02 02:49:33

问题


I like to overload my ampersand operator with paste. So that way I can paste stuff easily. Like this:

R> "Hello" & " World"
 [1] "Hello World"

And the way I achieve this is:

"&" <- function(...){paste(..., sep = "")}

This is all fine and dandy but you lose the ability to use ampersand as a natural "and" operator. What would be the best, fastest most beautiful way to overload my ampersand so that it recognizes when the inputs are logical?

TRUE & FALSE == FALSE

etc.


回答1:


You'll need to use the S3 object system in R:

`&` <- function(e1, e2) UseMethod("&", c(e1, e2))
`&.default` <- function(e1, e2) paste(e1, e2)
`&.logical` <- function(e1, e2) .Primitive("&")(e1, e2)

Now you can use & as you would expect:

> 1 & 2
[1] "1 2"
> TRUE & FALSE
[1] FALSE
> "Hello" & "World"
[1] "Hello World"
> 



回答2:


I think defining &.default to use paste is just wrong:

`&` <- function(e1, e2) UseMethod("&", c(e1, e2))
`&.default` <- function(e1, e2) .Primitive("&")(e1, e2)
`&.character` <- function(e1, e2) paste(e1, e2)
"Hello" & "World"
[1] "Hello World"
 1*0
#[1] 0
 1&0
#[1] FALSE
 1&1
#[1] TRUE


来源:https://stackoverflow.com/questions/21197443/overloading-ampersand-operator-in-r

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