R,深拷贝与浅拷贝,按引用传递 [英] R, deep vs. shallow copies, pass by reference

查看:27
本文介绍了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)

a 是按字面意思传递的还是对传递的引用?

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

x <- 1
y <- x

副本的参考?什么时候不是这样?

Reference of copy? When is this not the case?

如果有人可以向我解释这一点,我将不胜感激.

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

推荐答案

当它传递变量时,总是通过复制而不是通过引用.但是,有时,在实际发生分配之前,您不会得到副本.该过程的真实描述是pass-by-promise.看看文档

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 最近对 applyReduce 的评估规则进行了更改.这是参考新闻在这里宣布的:从 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 在评论中引用的有趣的论文现在在这里:

And the interesting paper cited by jhetzel in the comments is now here:

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

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