I am wondering if there is a way to "predefine" parameters to functions like lm, glmer(lme4), glm, or home made functions.
I'll try to show my question with a small dataframe
y1<-(rnorm(n = 100, mean = 0, sd = 1))
y2<-(rnorm(n = 100, mean = 4, sd = 1))
x1 <- letters[1:2]; x1<- rep(x1, times =50 )
x2 <- letters[2:3]; x1<- rep(x1, times =50 )
x3 <- letters[4:5]; x1<- rep(x1, times =50 )
df<-as.data.frame(cbind(y1,y2,x1,x2,x3));df$y1<-as.numeric(df$y1);df$y2<-as.numeric(df$y2)
then I can easily fit lm like this
model <- lm(y1 ~x1, data=df)
However, what I am interested in being able to do is something like this
#first define list of predictors
predictor_vector<- c("x1","x2","x3")
And then use the names (strings) as a parameter in the lm()
function.
In this example, I am using lm()
and attempting to dynamically construct the regression as so:
model <- lm(y1 ~predictor_vector[1], data=df)
model <- lm(y1 ~predictor_vector[2], data=df)
model <- lm(y1 ~predictor_vector[3], data=df)
The example above doesn't work.
I am very grateful for any input on this topic and hope my example and explanation is clear enough.