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 
}
}
4

2 回答 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
于 2012-12-18T18:08:28.717 回答
1

makeActiveBinding

您可以将 ls() 替换为例如不需要一元运算符的 LS

于 2013-12-22T08:24:39.003 回答