Reputation: 9
I am trying to save the summary outputs of a lm
into a data frame, "csv" or "txt" file. What I wanted to do is to use a lm
(and eventually glm
) with different dependent variables, but the same independent variables.
This is my code using lapply
for model fitting:
varlist <- names(NDVI)[2:244]
models <- lapply(varlist, function(x) {
lm(substitute(i ~ efectohuracan, list(i = as.name(x))), data = NDVI)})
If I save it as
write.csv(models,"models.csv")
I get this error
Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors =
stringsAsFactors) : cannot coerce class ""lm"" to a data.frame
I am very new in R. The code I made it thanks to people who has posted their problems also in this community, so maybe there are better ways to approach this.
Thank you in advance
Upvotes: 1
Views: 3746
Reputation: 73295
Sorry I wrongly closed this as a dupe at the beginning. Thanks to my friend for reopening it.
For "mlm"
model class this is very efficient.
First, you need to Fitting a linear model with multiple LHS
Then let fit
be your fitted model object (of "mlm"
and "lm"
class), extract its coefficients by
beta <- coef(summary(fit))
This is a list of coefficient tables.
Then, let's collapse it into a data frame:
tab <- do.call(rbind.data.frame, beta)
Now you just write this data frame into a "csv" file as usual.
As a quick test, you can use the toy dataset provided in the linked thread.
Upvotes: 1