更改标准 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 分配一个新环境?