R унарная перегрузка оператора: риски?
В моем постоянном стремлении избежать использования круглых скобок для некоторых простых команд я написал следующий оператор для создания нового графического окна. Мой вопрос: я рискую "сломать" что-либо в R, кроме очевидной неспособности выполнить функцию "не" на моей переменной "newdev"?
# 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
}
}
Ответы
Ответ 1
Я выполнил "!" = 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
Ответ 2
с
makeActiveBinding
вы можете заменить ls(), например, LS без необходимости унарных операторов