data.table - data table calculating columns with dependencies in R -


i have dt , desire compute easy stock balances shown. computations easy , immediate in excel, allows recursive computations.

library(data.table) dt <- data.table(expand.grid(8:9, 0:59, 1:4)) names(dt) <- c("hour", "minute", "shop")  set.seed(1234) dt <- dt[, ':=' (demand = rpois(1, lambda = 0.8),                  stock_in = rpois(1, lambda = 0.05)*250                  ), by=names(dt)]  dt$stock_before <- na dt$stock_after <- na dt$sells <- na dt$lost_sells <- na  dt$stock_before[which(dt$hour == 8 & dt$minute == 0)] <- c(21, 45, 31, 50)   dt <- dt[order(dt$hour, dt$minute, dt$shop),] 

the desired format done, using tapply slow. tried use data table syntax better.

since stock_before of minute stock_after of minute before, line designed reports error. command use following lines:

dt <- dt[, ':=' (   stock_after =  max(0, stock_before+stock_in-demand),   stock_before  = shift(stock_after, 1),   sells = min(stock_before + stock_in, demand, na.rm=t),   lost_sells = max(demand-sells, 0)   ), by=shop] 

and error following:

error in shift(stock_after, 1) : object 'stock_after' not found in addition: warning message: in `[.data.table`(dt, , `:=`(stock_after = max(0, stock_before +  :   invalid .internal.selfref detected , fixed taking (shallow) copy of  data.table := can add new column reference. @ earlier  point, data.table has been copied r (or been created manually using structure() or similar). avoid key<-,   names<- , attr<- in r (and oddly)   may copy whole data.table. use set* syntax instead avoid copying: ?set,   ?setnames , ?setattr. also, in r<=v3.0.2, list(dt1,dt2) copied entire dt1   , dt2 (r's list() used copy named objects); please upgrade r>v3.0.2 if  biting. if message doesn't help, please report datatable-help root cause can fixed. 

the results show below:

head(dt, 12)     hour minute shop demand stock_in stock_before stock_after sells lost_sells 1     8      0    1      0        0           21          21     0          0 2     8      0    2      0        0           45          45     0          0 3     8      0    3      1        0           31          30     1          0 4     8      0    4      2        0           50          48     2          0 5     8      1    1      2        0           21          19     2          0 6     8      1    2      3        0           45          42     3          0 7     8      1    3      0        0           30          30     0          0 8     8      1    4      1      250           48         297     1          0 9     8      2    1      1        0           19          18     1          0 10    8      2    2      3        0           42          39     3          0 11    8      2    3      1        0           30          29     1          0 12    8      2    4      0      250          297         547     0          0 

can me? lot!


Comments