2
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.

89_Simple
  • 3,393
  • 3
  • 39
  • 94

1 Answers1

1

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
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    I feel like there _has_ to be a more elegant solution than this, but hey, at least it works. – daknowles Oct 10 '18 at 23:47
  • Yup: https://stackoverflow.com/questions/5774813/short-formula-call-for-many-variables-when-building-a-model – dmh Nov 25 '19 at 01:10