且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

R 如何处理函数调用中的对象?

更新时间:2023-01-12 15:06:00

x 是在全局环境中定义的,而不是在您的函数中.

x is defined in the global environment, not in your function.

如果您尝试修改函数中的非局部对象,例如 x,则 R 会制作该对象的副本并修改该副本,因此每次运行匿名函数时都会复制 x 被制作并且它的第 i 个分量被设置为 4.当函数退出时,制作的副本永远消失.原x没有修改.

If you try to modify a non-local object such as x in a function then R makes a copy of the object and modifies the copy so each time you run your anonymous function a copy of x is made and its ith component is set to 4. When the function exits the copy that was made disappears forever. The original x is not modified.

如果我们要写 x[i] <<- i 或者如果我们要写 x[i] 然后 R 会写回它.另一种写回它的方法是将 e 设置为存储 x 的环境并执行以下操作:

If we were to write x[i] <<- i or if we were to write x[i] <- 4; assign("x", x, .GlobalEnv) then R would write it back. Another way to write it back would be to set e, say, to the environment that x is stored in and do this:

e <- environment()
sapply(1:10, function(i) e$x[i] <- 4)

或者可能是这样:

sapply(1:10, function(i, e) e$x[i] <- 4, e = environment())

通常不会在 R 中编写这样的代码.而是将结果作为函数的输出产生,如下所示:

Normally one does not write such code in R. Rather one produces the result as the output of the function like this:

x <- sapply(1:10, function(i) 4)

(实际上在这种情况下可以写x[] .)

(Actually in this case one could write x[] <- 4.)

添加:

使用 proto 包可以做到这一点,其中方法 f 设置了 x 属性改为 4.

Using the proto package one could do this where method f sets the ith component of the x property to 4.

library(proto)

p <- proto(x = 1:10, f = function(., i) .$x[i] <- 4)

for(i in seq_along(p$x)) p$f(i)
p$x

添加:

在上面添加了另一个选项,我们在其中显式传递存储 x 的环境.

Added above another option in which we explicitly pass the environment that x is stored in.