Use mapply to fit list of lm models to list of data frames [R]
Is this possible? I can get mapply
to work with the help
examples, but I can't get a trivial example with lm
to work. Here's my attempt which returns a matrix, instead of a list of lm
objects.
temp.df <- list(
开发者_C百科 data.frame(a = rep(1:10, each = 10), b = 1:100, c = rnorm(100), d = rnorm(100, 2))
)
temp.df[[2]] <- subset(temp.df[[1]], a > 2)
temp.mod <- list(a ~ b,
a ~ b + c,
a ~ b + c + d)
temp.lm <- mapply(lm, formula = temp.mod, data = temp.df[c(1,1,2)])
temp.sum <- lapply(temp.lm, summary)
Should I just stick with lapply
and specifying data =
each time? Thanks!
Not sure what you mean by specifying data each time, but if you pack everything into a bigger (nested) list, and write your own wrapper function that calls lm() and summary(), lapply is a good option:
bigList <- list(m1=list(dat=temp.df[[1]],mod=temp.mod[[1]]),
m1=list(dat=temp.df[[2]],mod=temp.mod[[2]]))
fitLM <- function(x){
lm1 <- lm(x$mod,data=x$dat)
return(summary(lm1))
}
temp.lm <- lapply(bigList,FUN=fitLM)
Edit: Just to follow up on the mapply behavior, when I run your code, I get a 12x3 matrix that actually does contain all the relevant lm object information, but the class attribute has been lost. Resetting that and then lapply-ing summary() works with your original code, I believe. But I think a nested list of arguments and lapply() is simpler in this case.
lmList <- list(a=temp.lm[,1],b=temp.lm[,2],c=temp.lm[,3])
lmList <- lapply(lmList,function(x){class(x) <- "lm";return(x)})
temp.sum <- lapply(lmList, summary)
精彩评论