让我们拥有:
library(R6); library(data.table); library(xts)
Portfolio <- R6Class("Portfolio",
public = list(name="character",
prices = NA,
initialize = function(name, instruments) {
if (!missing(name)) self$name <- name
}
))
p = Portfolio$new("ABC")
DT = data.table(a=1:3, b=4:6)
X = xts(1:4, order.by=as.Date(1:4))如果我们在对象槽中分配一个data.table,然后修改外部数据表,那么对象槽中的数据表也会通过引用进行修改:
p$prices = DT
p$prices
DT[a==1,b:=10] # modify external table
p$prices # verify that the slot data is modified by reference让我们用xts做一个类似的实验
p$prices = X
p$prices
X["1970-01-03"] <- 10 # modify the external xts
p$prices # observe that modification didn't take place inside the object以这种方式在对象槽内分配xts对象似乎破坏了槽和外部对象之间的链接,这与data.table不同。
是否可以通过引用来实现xts的共享?
发布于 2014-09-26 09:10:36
在这里,您所显示的内容实际上与data.table分配行为有关,而且在任何情况下都与R6类相关。实际上,data.table分配是通过引用完成的(独立于R6字段中复制),或者xts对象只是被复制。
您是否希望在所有Portofolio对象之间创建xts对象作为共享对象?
举个例子:
XtsClass <- R6Class("XtsClass", public = list(x = NULL))
Portfolio <- R6Class("Portfolio",
public = list(
series = XtsClass$new()
)
)
p1 <- Portfolio$new()
p1$series$x <- xts(1:4, order.by=as.Date(1:4))
p2 <- Portfolio$new()p2和p1共享同一个xts对象。现在,如果您在p2中修改它,您将得到p1中的smae修改,因为series是一个在R6对象的所有实例之间共享的引用对象。
p2$series$x["1970-01-03"] <- 10
p1$series$x
[,1]
1970-01-02 1
1970-01-03 10 ## here the modification
1970-01-04 3
1970-01-05 4https://stackoverflow.com/questions/26054372
复制相似问题