【问题标题】:R unary operator overload: risks?R 一元运算符重载:风险?
【发布时间】:2012-10-23 02:35:49
【问题描述】:

为了避免在一些简单命令中使用括号,我编写了以下运算符来创建一个新的图形窗口。我的问题是:除了明显无法对变量“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 
}
}

【问题讨论】:

  • 您是否会直接在命令提示符下使用这些简单的命令(即,不将它们嵌入函数或其他内容中)?如果是这样,您可以创建一个新类并为该类定义一个打印方法,该方法可以满足您的需求。
  • 如果我想创建图表集合,我认为很有可能我会在函数中调用这些命令,例如

标签: r operator-overloading


【解决方案1】:

makeActiveBinding

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

【讨论】:

  • 这是一个很好的观点,事实上我用于一些“快速”功能。我最终更喜欢发布的方法,因为我用switch 函数重写了它——请参阅包cgwtoolssplatnd 的源代码。
【解决方案2】:

我执行了"!" = 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 中的默认行为如果您只输入闭包的名称,则将闭包代码打印到控制台)
  • 补充一点:以交互方式定义或在.Rprofile 中定义的函数进入globalenv() - 包中的函数看不到它们。但是,您在.RProfile 中可能拥有的任何其他 功能都会受到影响。
猜你喜欢
  • 2011-09-18
  • 2010-10-21
  • 1970-01-01
  • 1970-01-01
  • 2014-11-18
  • 1970-01-01
  • 2020-02-24
  • 1970-01-01
相关资源
最近更新 更多