R,深对浅拷贝,通过参考 [英] R, deep vs. shallow copies, pass by reference

查看:171
本文介绍了R,深对浅拷贝,通过参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解逻辑R在向函数传递参数时使用,创建关于内存使用的变量副本等。它什么时候实际创建一个变量的副本,而只是传递一个引用该变量?特别是我很好奇的情况是:

I would like to understand the logic R uses when passing arguments to functions, creating copies of variables, etc. with respect to the memory usage. When does it actually create a copy of the variable vs. just passing a reference to that variable? In particular the situations I am curious about are:

f <- function(x) {x+1}
a <- 1
f(a)

/ code>是按字面传递的,还是对正在传递的引用?

Is a being passed literally or is a reference to a being passed?

x <- 1
y <- x

如果有人可以向我解释这一点,我会非常感激。

If someone could explain this to me I would highly appreciate.

推荐答案

当它传递变量时,它总是由副本而不是引用。然而,有时,你不会得到一个副本,直到作业实际发生。对流程的真实描述是通过承诺。查看文档

When it passes variables, it is always by copy rather than by reference. Sometimes, however, you will not get a copy made until an assignment actually occurs. The real description of the process is pass-by-promise. Take a look at the documentation

?force
?delayedAssign

一个实际的含义是,如果不是不可能避免至少需要至少两倍的RAM作为你的对象名义上占据,是非常困难的。修改一个大对象通常需要一个临时副本。

One practical implication is that it is very difficult if not impossible to avoid needing at least twice as much RAM as your objects nominally occupy. Modifying a large object will generally require making a temporary copy.

更新:2015年:我做(并确实)同意Matt Dowle的data.table包提供了一个备用路由到避免复制重复问题的分配。如果这是更新请求,那么我在建议的时候不明白。

update: 2015: I do (and did) agree with Matt Dowle that his data.table package provides an alternate route to assignment that avoids the copy-duplication problem. If that was the update requested, then I didn't understand it at the time the suggestion was made.

评估中R 3.2.1的最近更改规则 apply 减少。它是参考这里的新闻SO宣布:从lapply返回匿名函数 - 出现了什么问题?

There was a recent change in R 3.2.1 in the evaluation rules for apply and Reduce. It was SO-announced with reference to the News here: Returning anonymous functions from lapply - what is going wrong?

jhetzel在评论中引用的感兴趣的文章现在在这里

这篇关于R,深对浅拷贝,通过参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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