你可以在 R 中传递引用吗? [英] Can you pass-by-reference in R?
问题描述
你能用R"传递引用吗?例如,在以下代码中:
Can you pass by reference with "R" ? for example, in the following code:
setClass("MyClass",
representation(
name="character"
))
instance1 <-new("MyClass",name="Hello1")
instance2 <-new("MyClass",name="Hello2")
array = c(instance1,instance2)
instance1
array
instance1@name="World!"
instance1
array
输出是
> instance1
An object of class "MyClass"
Slot "name":
[1] "World!"
> array
[[1]]
An object of class "MyClass"
Slot "name":
[1] "Hello1"
[[2]]
An object of class "MyClass"
Slot "name":
[1] "Hello2"
但我希望它是
> instance1
An object of class "MyClass"
Slot "name":
[1] "World!"
> array
[[1]]
An object of class "MyClass"
Slot "name":
[1] "World!"
[[2]]
An object of class "MyClass"
Slot "name":
[1] "Hello2"
有可能吗?
推荐答案
否.
赋值语句中的对象是不可变的.R 将复制对象而不是只是引用.
Objects in assignment statements are immutable. R will copy the object not just the reference.
> v = matrix(1:12, nrow=4)
> v
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
> v1 = v
> v1[,1] # fetch the first column
[1] 1 2 3 4
(附带条件:上述陈述适用于 R 原语,例如向量、矩阵),也适用于函数;我不能肯定它是否适用于所有 R 对象——只是其中的大部分,以及绝大多数最常用的对象.)
(proviso: the statement above is true for R primitives, e.g., vectors, matrices), and also for functions; I cannot say for certain whether it's true for all R objects--just most of them, as well as the vast majority of the ones most often used.)
如果您不喜欢这种行为,您可以在 R 包的帮助下选择退出.例如,有一个名为 R.oo 的 R 包,它允许您模仿传递引用行为;R.oo 可在 CRAN 上使用.
If you don't like this behavior you can opt out of it with the help from an R Package. E.g., there is an R Package called R.oo that allows you to mimic pass-by-reference behavior; R.oo is available on CRAN.
这篇关于你可以在 R 中传递引用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!