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:
- it prints to screen
y.tsandz.ts; - the objects are created only in the
jenvironment 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?
<<-is justifiable, if somewhat opaque.Whatever you do in
j, unless you are using:=, if you don’t assign the result ofDT[]to something, you end up printing the result of what`DT[]evaluates to (the result of thejargument in these casesy.tsandz.tsand respectively.Just wrap these calls in invisible, and it won’t print, or make the outcome something else
Using invisible
Evaulating
jto something else (assigning along the way)In which case the results will be
'Assigned y.ts and x.ts to global environment)'and'assigned x.ts'respectively.