I have a data table that looks something like this, and I want to apply to it function f
library(data.table)
dt <- data.table(id= c(1,1,1,2,2,2,3,3,3), year=c(1,2,3,1,2,3,1,2,3),y = rnorm(9), x1 = rnorm(9), x2 = c(0,0,0,0,1,0,1,1,1),c2 = rnorm(9))
f <- function(data, var1, var2){
data[,(paste("times",var1,var2, sep = "_")) := get(var1)*get(var2)]
}
I would like to apply f over multiple variables obtaining results similar to the one below:
vars<-c("x1","x2","c2")
dt2<-lapply(vars, function(x) f(dt,"y", x))
dt2<-do.call(rbind,dt2)
I would like to obtain the same results using a for loop instead of lapply, unfortunately, I am not good with loops. Could anyone help me?
so far I tried the following but it does not work properly.
for(i in vars) {
dt<-f(dt,"y",i)
}
Thanks a lot in advance for your help
lapplyapproach as it works with other data. This is why I am looking for a different approach that uses a for loop. Any answer that would reproduce the results in dt2 of the example using a for loop would work. I will update the question to make it clearer