Thursday, 15 August 2013

r - Global silent assignments from within a data.table -



r - Global silent assignments from within a data.table -

i working several time series , characteristic in data.table in long format , build several different types of xts object exploiting data.table syntax. here 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), = c(1, -1), x = <- rnorm(10), y = 2 * + rnorm(10), z = 3 * + rnorm(10))

lets (try to) build 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)), = dat][ # operate on columns of datatable , z.ts <- xts(sz, order.by = dat)] # build xts

this code has 2 problems:

it prints screen y.ts , z.ts; the objects created in j environment not in global environment.

to solve (2), 1 can name objects in global enviroment , utilize <<-:

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)), = 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 create type of assignment within info table silent? utilize of <<- justified or there improve way of doing this?

<<- justifiable, if opaque.

whatever in j, unless using :=, if don't assign result of dt[] something, end printing result of `dt[] evaluates (the result of j argument in these cases y.ts , z.ts , respectively.

just wrap these calls in invisible, , won't print, or create outcome 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)), = dat][ , z.ts <<- xts(sz, order.by = dat)])

evaulating j else (assigning along 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 , x.ts global environment)' } ] dt[ , list(sz = mean(z/x)), = dat][ , {z.ts <<- xts(sz, order.by = dat) 'assigned x.ts'}]

in case results 'assigned y.ts , x.ts global environment)' , 'assigned x.ts' respectively.

r data.table xts

No comments:

Post a Comment