爲了避免對一些簡單的命令使用圓括號,我寫了下面的操作符來創建一個新的圖形窗口。我的問題是:除了明顯無法在變量「newdev」上執行「not」函數之外,我是否有可能「破壞」R中的任何內容?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
我認爲如果我想要創建一個圖表集合,例如在函數內調用這些命令的機會很大, –