Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using stargazer with a list of lm objects created by lapply-ing over a split data.frame

Tags:

r

stargazer

I'm trying to create a stargazer table for a set of regressions, where I ran each regression on a subset of my data. The natural way to do this, I would think, is to use split to create a list of data.frames from my data, create a list of lm objects by using lapply on the list of data.frames, and then feed that list to stargazer. For example,

library(MASS)
library(stargazer)

data(Boston)

# This doesn't work
by.river <- split(Boston, Boston$chas)
fit <- lapply(by.river, lm, formula = crim ~ indus)
stargazer(fit, type = "text")

# % Error: Unrecognized object type.
# % Error: Unrecognized object type.

If I divide them up manually, this works fine:

# This works
fit2 <- vector(mode = "list", length = 2)
fit2[[1]] <- lm(crim ~ indus, data = Boston, subset = (chas == 0))
fit2[[2]] <- lm(crim ~ indus, data = Boston, subset = (chas == 1))
stargazer(fit2, type = "text")

But with my real data, the thing I'm splitting by has several values, and I would rather not split them all up by hand. Any ideas why I'm getting the "% Error: Unrecognized object type." error?

like image 549
Jake Fisher Avatar asked Jan 13 '15 20:01

Jake Fisher


1 Answers

There is an easy workaround, hinted at by BondedDust and suggested by careful perusal of the help for lapply.

fit <- lapply(by.river, function(dd)lm(crim ~ indus,data=dd))
stargazer(fit, type = "text")
fit[[1]]$call
#lm(formula = crim ~ indus, data = dd)
like image 54
atiretoo Avatar answered Oct 09 '22 12:10

atiretoo