Search code examples
rdata.tablextsr6

xts assignment by reference


Let's have:

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 a data.table into the object slot and then modify the external data table, the data table in the object slot is modified by reference as well:

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

Let's 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 xts object inside the object slot this way seems to break the link between the slot and external object, unlike with data.table.

Is it somehow possible to achieve that xts is shared by reference?


Solution

  • Here what you show is really related to data.table assignment behavior and in any case is related to R6 classes. Indeed, data.table assignment is done by reference( independently that this is copied in R6 field) or xts object are just copied.

    Are you looking to create an xts object as a shared object between all your Portofolio objects?

    Here an exemple:

        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 and p1 share the same xts object. Now if you modify it in p2 you will get the smae modification in p1, since series is a reference object that is shared across all instances of the R6 objects.

        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