R 如何处理函数调用中的对象? [英] How does R handle object in function call?

查看:66
本文介绍了R 如何处理函数调用中的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 Java 和 Python 背景,最近在学习 R.

I have background of Java and Python and I'm learning R recently.

今天我发现 R 处理对象的方式似乎与 Java 和 Python 完全不同.

Today I found that R seems to handle objects quite differently from Java and Python.

例如以下代码:

x <- c(1:10)
print(x)
sapply(1:10,function(i){
            x[i] = 4
        })
print(x)

代码给出如下结果:

[1]  1  2  3  4  5  6  7  8  9 10
[1]  1  2  3  4  5  6  7  8  9 10

但我希望输出的第二行都是4",因为我修改了 sapply 函数中的向量.

But I expect the second line of output to be all '4' since I modified the vector in the sapply function.

这是否意味着 R 在函数调用中复制对象而不是对对象的引用?

So does this mean that R make copies of objects in function call instead of reference to the objects?

推荐答案

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] <- 4;assign("x", x, .GlobalEnv) 然后 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[] <- 4.)

(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.

这篇关于R 如何处理函数调用中的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆