Apologies for such a rudimentary question–I must be missing something obvious.
I want to build a list of lm objects, which I’m then going to use in an llply call to perform mediation analysis on this list. But this is immaterial–I just first want to make a list of length m (where m is the set of models) and each element within m will itself contain n lm objects.
So in this simple example
d1 <- data.frame(x1 = runif(100, 0, 1),
x2 = runif(100, 0, 1),
x3 = runif(100, 0, 1),
y1 = runif(100, 0, 1),
y2 = runif(100, 0, 1),
y3 = runif(100, 0, 1))
m1 <- lm(y1 ~ x1 + x2 + x3, data = d1)
m2 <- lm(x1 ~ x2 + x3, data = d1)
m3 <- lm(y2 ~ x1 + x2 + x3, data = d1)
m4 <- lm(x2 ~ x1 + x3, data = d1)
m5 <- lm(y3 ~ y1 + y2 + x3, data = d1)
m6 <- lm(x3 ~ x1 + x2, data = d1)
I want a list containing 3 elements, and the first element will contain m1 and m2, the second will contain m3 and m4, etc. My initial attempt is sort of right, but the lmm objects don’t retain their class.
mlist <- list(c(m1,m2),
c(m3,m4),
c(m5,m6))
It has the right length (ie length(mlist) equals 3), but I thought I could access the lm object itself with
class(mlist[1][[1]])
but this element is apparently a list.
Am I screwing up how I build the list in the first step, or is this something more fundamental regarding lm objects?
No, you’re just getting confused with
cand list indexing. Try this:So
cwill concatenate lists by flattening them. In the case of almobject, that basically means it’s flattening eachlmobject in a list of each of the object components, and then concatenating all those lists together.cis more intuitively used on atomic vectors.The indexing of lists often trips people up. The thing to remember is that
[will always return a sub-list, while[[selects an element.In my example above, this means that
mlist[1]will return a list of length one. That first element is still a list. So you’d have to do something likemlist[1][[1]][[1]]to get all the way down to thelmobject that way.