Xts assignment by reference

Let be:

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

If we assign data.tableto the object slot and then change the external data table, the data table in the object slot will also be changed by reference:

p$prices = DT
p$prices
DT[a==1,b:=10] # modify external table
p$prices # verify that the slot data is modified by reference

Do a similar experiment with 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

Assigning an object xtsinside an object slot in this way seems to break the connection between the slot and the external object, unlike data.table.

How can one achieve that xtssharing a link?

+4
source share
1 answer

, , data.table R6. , data.table ( , R6) xxts .

xts Portofolio?

:

    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, smae p1, 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    4
+2

All Articles