本文介绍了重载&符R中的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢给&符操作符添加过多的粘贴.这样一来,我可以轻松粘贴内容.像这样:

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 = "")}

这一切都很好,但您却失去了使用与号作为自然"and"运算符的能力.什么是最好的,最快的最漂亮的方式来使我的&"号过载,以便它可以识别输入何时是逻辑上的?

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

推荐答案

您需要在R中使用S3对象系统:

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"
>

这篇关于重载&符R中的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 00:34
查看更多