为什么我不能改变S4方法的环境?

时间:2013-05-06 23:30:45

标签: r s4

更改标准R函数的环境非常简单:

foo <- function(x) x + z
env0 <- new.env()
env0$z <- 0
environment(foo) <- env0
z <- 1
foo(3)

但是,无法在S4方法上执行相同类型的分配:

setClass(Class = "MyClass", 
  representation = representation(
    x = "numeric"
  )
)

myClass <- function(n) {
  new("MyClass",
    x = rnorm(n)
  )
}

setGeneric(
  name = "foo",
  def = function(object) {standardGeneric("foo")}
)
setMethod(
  f = "foo", 
  signature = "MyClass",
  definition = function(object) {
    sqrt(abs(xx))
  }
)

# Here everything is Ok
showMethods("foo")

e1 <- new.env()
e1$xx <- st@x
environment(foo) <- e1

# After the environment assignment foo is no longer a method of class MyClass
showMethods("foo")

有没有办法为方法foo分配新环境?

0 个答案:

没有答案