可以在R中通过引用吗?

您可以通过引用加上“ R”吗?例如,在以下代码中:


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"

可能吗 ?


守着星空守着你
浏览 544回答 3
3回答

蓝山帝景

没有。赋值语句中的对象是不可变的。R将复制对象,而不仅仅是引用。> v = matrix(1:12, nrow=4)> v&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[,1] [,2] [,3]&nbsp; &nbsp; &nbsp;[1,]&nbsp; &nbsp; 1&nbsp; &nbsp; 5&nbsp; &nbsp; 9&nbsp; &nbsp; &nbsp;[2,]&nbsp; &nbsp; 2&nbsp; &nbsp; 6&nbsp; &nbsp;10&nbsp; &nbsp; &nbsp;[3,]&nbsp; &nbsp; 3&nbsp; &nbsp; 7&nbsp; &nbsp;11&nbsp; &nbsp; &nbsp;[4,]&nbsp; &nbsp; 4&nbsp; &nbsp; 8&nbsp; &nbsp;12> v1 = v> v1[,1]&nbsp; &nbsp; &nbsp;# fetch the first column&nbsp;&nbsp; &nbsp; &nbsp;[1] 1 2 3 4(附带条件:上面的陈述对R个原语,例如向量,矩阵)是正确的,对函数也是如此; 我不能肯定地说所有 R对象-包括大多数对象,以及大多数最常用的对象都适用。如果您不喜欢这种行为,可以在R软件包的帮助下选择退出。例如,有一个名为R.oo的R包,它可以让您模仿按引用传递行为。R.oo在CRAN上可用。

子衿沉夜

正如一些人之前指出的,这可以通过使用class对象来完成environment。存在使用environments 建立的正式方法。它称为参考类,使您的工作变得非常简单。检查?setRefClass主条目帮助页面。它还描述了如何在引用类中使用形式方法。例setRefClass("MyClass",&nbsp; &nbsp; fields=list(&nbsp; &nbsp; &nbsp; &nbsp; name="character"&nbsp; &nbsp; ))instance1 <- new("MyClass",name="Hello1")instance2 <- new("MyClass",name="Hello2")array = c(instance1,instance2)instance1$name <- "World!"输出量> instance1Reference class object of class "MyClass"Field "name":[1] "World!"> array[[1]]Reference class object of class "MyClass"Field "name":[1] "World!"[[2]]Reference class object of class "MyClass"Field "name":[1] "Hello2"
打开App,查看更多内容
随时随地看视频慕课网APP