How to loop data.table function through table

38 views Asked by At

I would like to get the moving average of all columns in my data set. I've found the following code to work to achieve this:

library(data.table)
setDT(df)  
setkey(data1,column1, column2)
data1[,column3_l10:=as.numeric(lag(slide_dbl(column3, mean, .before = 10))),by=column2]
data1[,column4_l10:=as.numeric(lag(slide_dbl(column4, mean, .before = 10))),by=column2]
data1[,column5_l10:=as.numeric(lag(slide_dbl(column5, mean, .before = 10))),by=column2]
....

However there are many numeric columns in my dataset and I would like to create a function that would iterate through all the columns and get the moving average rather than adding them one by one. I've tried the following code however am receiving an error.

columns <- colnames(data1)

mean_func <- function(data, columns, group) {
  for(i in columns) {
    df[,paste0(get(i), "_l10") := as.numeric(lag(slide_dbl(get(i), mean, .before = 10))), by=group]
  }
}

mean_func(data = data1, columns = cols, group = "column2")


Error: Check that is.data.table(DT) == TRUE. Otherwise, :=, `:=`(...) and let(...) are defined for use in j, once only and in particular ways. See help(":=").

Apologies in advance if my question is not correctly formatted.

0

There are 0 answers