创建引用类的深层副本:不适用于列表字段?

时间:2014-08-28 14:33:50

标签: r list object reference

我正在尝试复制包含列表字段的引用类(foo)的实例。列表字段包含另一个类(bar)的实例。使用foo方法复制$copy()实例时,不会复制列表的实例并继续引用同一对象。下面的代码说明了这个问题。有没有解决的办法?我怎样才能做一个真正的深层复制?

bar<-setRefClass("bar", fields = list(name = "character"))
foo<-setRefClass("foo", fields = list(tcp_vector = "list"))


x1<-foo()
x1$tcp_vector <- list(bar(name = "test1"))

x1$tcp_vector[[1]]$name # equals "test1"

x2 <- x1$copy()

x2$tcp_vector[[1]]$name # equals "test1"

x2$tcp_vector[[1]]$name <- "test2"  # set to "test2"

x2$tcp_vector[[1]]$name # equals "test2"

x1$tcp_vector[[1]]$name # also equals "test2"??

1 个答案:

答案 0 :(得分:1)

copy方法实际上只复制ReferenceClass个对象。您的foo课程只有一个字段list,而#34;正常&#34;字段不会被复制。这有效:

bar<-setRefClass("bar", fields = list(name = "character"))
foo<-setRefClass("foo", fields = list(tcp_vector = "bar"))
x1<-foo()
x1$tcp_vector <- bar(name = "test1")
x1$tcp_vector$name # equals "test1"
x2 <- x1$copy()

x2$tcp_vector$name # equals "test1"

x2$tcp_vector$name <- "test2"  # set to "test2"

x2$tcp_vector$name # equals "test2"
x1$tcp_vector$name # equals "test"

有关详细信息,请参阅帮助?setRefClass。如果你想保留在OP中定义的foo类,我想你必须在创建bar的副本之前手动复制任何x1对象。