R一元运算符重载:风险?

19

在我持续避免在一些简单的命令中使用括号的追求中,我编写了以下操作符来创建一个新的图形窗口。我的问题是:除了无法对变量“newdev”执行“not”函数之外,我是否有破坏R中其他任何内容的风险?

# function to overload "!" for one purpose only
#this is adapted  from the sos package code for "???", credited to Duncan Murdoch.
# Example of how to create a specialized unary  operator that doesn't require
# parentheses for its argument.  So far as I can tell,  
#the only way to do this is to overload an existing function or
# operator which doesn't require parentheses.  "?" and "!" meet this requirement.
`!` <- function (e1, e2)  { 
call <- match.call()
#  match.call breaks out each callable function in argument list (which was "??foo" for the sos package "???",
 #  which allows topicExpr1 to become  a list variable w/ callable function "!"  (or "?" in sos) 
original <- function() { 
    call[[1]]<-quote(base::`!`)
    return(eval(call, parent.frame(2)))
}

   # this does preclude my ever having an actual
   # variable called "newdev" (or at least trying to create the actual NOT of it) 
if(call[[2]] =='newdev') {
    windows(4.5,4.5,restoreConsole=T)
}else{
    return(original())  # do what "!" is supposed to do 
}
}

你是否只是直接在命令提示符下使用这些简单的命令(即不将它们嵌入到函数或其他内容中)?如果是这样,你可以创建一个新类,并为该类定义一个打印方法,以实现你想要的功能。 - BenBarnes
如果我想要创建一个图表集合,我认为很有可能在函数内调用这些命令。 - Carl Witthoft
2个回答

5
我执行了"!" = function(a){stop("'NOT' is used")},并执行了使用!运算符的replications函数,这个操作正常工作。所以覆盖"!"应该是安全的。
不过你可能仍然想使用类,做法如下:
# Create your object and set the class
A = 42
class(A) = c("my_class")

# override ! for my_class
"!.my_class" = function(v){ 
  cat("Do wathever you want here. Argument =",v,"\n")
}

# Test ! on A
!A

好的一点是,虽然这不能满足我的意图,即在不必在闭包后输入“()”的情况下执行一个特定的不需要参数的闭包。例如,使用!ls代替ls()。是的,我就是那么懒 :-)(请记住,在R中,如果您只输入闭包的名称,则默认行为是将闭包代码打印到控制台) - Carl Witthoft
3
此外,需要补充的是:在交互式定义或者在你的 .Rprofile 中定义的函数将放置于 globalenv() 中,因此包中的函数无法访问它们。但是,任何你在.RProfile中拥有的其他函数都会受到影响。 - Owen

1

使用

makeActiveBinding

您可以将ls()替换为例如LS,无需使用一元运算符


这是一个很好的观点,实际上我用它来编写一些“快速”函数。但最终我更喜欢发布的方法,因为我使用了switch函数进行重写 - 请参见包cgwtoolssplatnd的源代码。 - Carl Witthoft

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接