# [R] how to feed lme() and lmer() data for a loop

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Tue Feb 25 10:21:11 CET 2020

```Hello,

Not possible with lmer? I think it is.
At least with the first example of ?lmer it is:

library(lme4)

Days <- sleepstudy\$Days
data2 <- data.frame(X = Days, Y = Days, Z = Days)

nc <- ncol(data2)
lmer_list <- vector("list", length = nc)

for(i in seq.int(nc)){
#fm1 <- lmer(Reaction ~ Days + (Days | Subject), sleepstudy)
fm1 <- lmer(sleepstudy[, 1] ~ data2[, i] + (data2[, i] | sleepstudy[,
3]))
lmer_list[[i]] <- fm1
}

Anyway, if your subsetting is based on an index, consider coercing the
data.frame to (numeric) matrix first, it will speed up things.
And use the standard way with a data argument for the other terms:

data2 <- as.matrix(data2)
lmer_list2 <- vector("list", length = nc)

for(i in seq.int(nc)){
#fm1 <- lmer(Reaction ~ Days + (Days | Subject), sleepstudy)
fm1 <- lmer(Reaction ~ data2[, i] + (data2[, i] | Subject), data =
sleepstudy)
lmer_list2[[i]] <- fm1
}

lmer_list[[1]]
lmer_list2[[1]]

Hope this helps,

Às 08:33 de 25/02/20, Federico Calboli escreveu:
> Hi all,
>
> I am struggling with an issue related to lme() and lmer().  lm() can easily take stuff on the fly from different objects and be happy:
>
> lm(data1[,1] ~ data2[,1] + data3[,45] + data4[,39])
>
> works — always.  It also allows me to run nice loops:
>
> for(i in 1:whatever){
> lm(data1[,1] ~ data2[,i] + data3[,45] + data4[,39])
> }
>
> (for a useless but clear example where I loop the model over all columns of data2).  This property also allows me to totally ignore ’names’ for the data I am using.
>
> I am at loss why this is not possible with lme() or lmer().  I can go around this issue by building data frames on the fly, but this is cumbresome, both as code and very likely as performance, especially looping over lots of data having to generate these dummy data frames.
>
> If there is a trick I am missing I’d be grateful if anybody could set me straight.
>
> Best
>
> F
>
>
> --
> Federico Calboli
> LBEG - Laboratory of Biodiversity and Evolutionary Genomics
> Charles Deberiotstraat 32 box 2439
> 3000 Leuven
> +32 16 32 87 67
>
>
>
>
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help