1

I am working with several time series and their characteristic in a data.table in long format and I would like to construct several different types of xts object exploiting the data.table syntax. Here is what I have in mind:

Some preliminary data

library(data.table)
set.seed(1)
DT <- data.table(
  dat = as.Date("2013-01-01") + rep(1:5, 2),
  a = c(1, -1),
  x = i <- rnorm(10),
  y = 2 * i + rnorm(10),
  z = 3 * i + rnorm(10))

Lets (try to) construct 3 different time series

DT[a == 1,{
  x.ts <- xts(x, order.by = dat)
  y.ts <- xts(y, order.by = dat)
  }]
DT[
  , list(sz = mead(z/x)), by = dat][   # operate on columns of the datatable
  , z.ts <- xts(sz, order.by = dat)]    # construct xts

This code has two problems:

  1. it prints to screen y.ts and z.ts;
  2. the objects are created only in the j environment not in the global environment.

To solve (2), one can name the objects in the global enviroment and use <<-:

x.ts <- y.ts <- z.ts <- NA
DT[a == 1,{
  x.ts <<- xts(x, order.by = dat)
  y.ts <<- xts(y, order.by = dat)
  }
]
DT[
  , list(sz = mean(z/x)), by = dat][
  , z.ts <<- xts(sz, order.by = dat)]

And indeed

> z.ts
               [,1]
2013-01-02 2.300730
2013-01-03 4.969685
2013-01-04 1.959377
2013-01-05 1.961270
2013-01-06 3.256254

How can I make this type of assignment within a data table silent? Is this use of <<- justified or there is a better way of doing this?

Ryogi
  • 5,497
  • 5
  • 26
  • 46

1 Answers1

2

<<- is justifiable, if somewhat opaque.

Whatever you do in j, unless you are using :=, if you don't assign the result of DT[] to something, you end up printing the result of what `DT[] evaluates to (the result of the j argument in these cases y.ts and z.ts and respectively.

Just wrap these calls in invisible, and it won't print, or make the outcome something else

Using invisible

# 
x.ts <- y.ts <- z.ts <- NA
invisible(DT[a == 1,{
  x.ts <<- xts(x, order.by = dat)
  y.ts <<- xts(y, order.by = dat)
  }
])
invisible(DT[
  , list(sz = mean(z/x)), by = dat][
  , z.ts <<- xts(sz, order.by = dat)])

Evaulating j to something else (assigning along the way)

x.ts <- y.ts <- z.ts <- NA
DT[a == 1,{
  x.ts <<- xts(x, order.by = dat)
  y.ts <<- xts(y, order.by = dat)
  'Assigned y.ts and x.ts to global environment)'
  }
]
DT[
  , list(sz = mean(z/x)), by = dat][
  , {z.ts <<- xts(sz, order.by = dat)
      'assigned x.ts'}]

In which case the results will be 'Assigned y.ts and x.ts to global environment)' and 'assigned x.ts' respectively.

mnel
  • 113,303
  • 27
  • 265
  • 254