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 に答える