I am learning how to run functions. Hopefully, this would be an easy question to answer.
I have a df and I want to pass the function w to some of the variables in the df.
df <- data.frame(id= c(1,1,1,2,2,2,3,3,3), time=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))
library(data.table)
library(dplyr)
w<-function(data,var1,var2){
x <- substitute(var1)
y <- substitute(var2)
data<-setDT(data)[,paste("times",(var1), (var2), sep = "_"):=eval(var1)*eval(var2)]
}
df2<- w(df,y,x1)
When I apply the function to a single variable the function works. but I would like to apply it to a series of variables in my data frame, but for some reason, the function fails when I try to apply it to multiple variables at once. does anyone know how I could make it work?
So far I tried the following
vars<-c("x1","x2")
df3<- lapply(vars, function(x) w(df,y, x))
thanks a lot for your help