4

让我们:

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))

如果我们将 a 分配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通过引用共享?

4

1 回答 1

2

在这里,您显示的内容实际上与 data.table 分配行为有关,并且无论如何都与 R6 类有关。实际上,data.table 分配是通过引用完成的(独立于在 R6 字段中复制的)或 xts 对象只是被复制。

您是否希望创建一个 xts 对象作为所有 Portfolio 对象之间的共享对象?

这里有一个例子:

    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 修改,因为系列是在 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    4
于 2014-09-26T09:10:36.880 回答