您可以在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
( proviso :以上陈述适用于R 基元,例如向量,矩阵),也适用于函数;我不能肯定地说 all 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屋!