Search code examples
rdata.tableshift

Combining "shift"-function with calculation


I have the following data.table:

          Dates       variable   value
  1: 1985/01/02  SLB UN Equity  4.5192
  2: 1985/01/03  SLB UN Equity  4.3111
  3: 1985/01/04  SLB UN Equity  4.2963
  4: 1985/01/07  SLB UN Equity  4.2368
  5: 1985/01/08  SLB UN Equity  4.1327
 ---                                 

I would like to perform "n"-number of "shifts" to value-column, and then calculate the return by dividing value-column by each "shifted" column. I have managed the first part using:

dt[, paste("px.min.", 1:2, sep = "", "d") := shift(value, 1:2), by = variable][]

with the result being:

          Dates       variable   value px.min.1d px.min.2d
  1: 1985/01/02  SLB UN Equity  4.5192        NA        NA
  2: 1985/01/03  SLB UN Equity  4.3111    4.5192        NA
  3: 1985/01/04  SLB UN Equity  4.2963    4.3111    4.5192
  4: 1985/01/07  SLB UN Equity  4.2368    4.2963    4.3111
  5: 1985/01/08  SLB UN Equity  4.1327    4.2368    4.2963
 --- 

The 2nd part is causing the problem.

dt.px.melt[, paste("px.min.", 1:2, sep = "", "d") := value/shift(value, 1:2), by = variable][ ]

produces the error:

"Error in value/shift(value, 1:2) : non-numeric argument to binary operator"


Solution

  • You can use

    dt[, paste("px.min.", 1:2, sep = "", "d") := 
           lapply(shift(value, 1:2), function(x) value/x), by = variable][ ]
    

    The point being that you need to conduct the division operation column by column, which lapply will do for you