Reputation: 3805
library(lme4)
data("sleepstudy")
sleepstudy$x2 <- runif(length(sleepstudy$Reaction))
sleepstudy$x3 <- runif(length(sleepstudy$Reaction))
mdl <- lmer(Reaction ~ Days + x2 + x3 + (1|Subject), data = sleepstudy)
I want to know how to specify the above formulae in different way. As a context, my data frame consists of 1 dependent variable, 20 independent variables and 1 grouping variable that is used as a random effect. I do some preprocessing which basically reduces the number of the independent variables. However, I do know which of the 20 variables will be retained in advance. So is there any way to specify the above something like:
mdl <- lmer(sleepstudy[,"the first column"] ~ sleepstudy[, "all the other columns in the df"] + (1|"the last column"), data = sleepstudy)
The only thing I know that my first column will be my dependent variable, my last column will be random variable, and all the columns in the middle will be my predictors
EDIT
I have done this:
as.formula(paste("y~", paste(pred.names, collapse="+")))
pred.names
is the names of the final list of variables that I want to work with. Where do I put the random effect gorup
variable in the above formula.
Upvotes: 2
Views: 620
Reputation: 887881
Based on the description
sleepstudy <- sleepstudy[c(1:2, 4:5, 3)]
out <- lmer(formula(paste(names(sleepstudy)[1], '~',
paste(names(sleepstudy)[2:(ncol(sleepstudy)-1)], collapse=' + '),
'+ (1|', names(sleepstudy)[ncol(sleepstudy)], ')')), data = sleepstudy)
Note: Here, we assume that the last column is 'Subject'
Checking the output
mdl <- lmer(Reaction ~ Days + x2 + x3 + (1|Subject), data = sleepstudy)
all.equal(out, mdl)
#[1] TRUE
Upvotes: 1