Search code examples
rinterpretationlm

Exporting R lm model with multiple dependent variables to csv


I have the following lm with a vector of dependent variables:

fit<-lm(cbind(X1m, X3m, X6m, X1y, X2y, X3y, X5y, X6y, X10y, 
                 X20y, X30y) ~ (ff + dc), data = yields)

When attempting to export the entire output to a csv file, I get this error:

write.csv(summary(fit),"fit.csv")
Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = stringsAsFactors) :     
cannot coerce class ""listof"" to a data.frame

Exporting the coefficients only yields no error:

write.csv(coef(fit), "fit.csv")

I would like, however, to have t-statistics and standard errors along with my coefficients in a neatly formatted csv, so as to copy into word documents, presentations, etc.

I know this problem has to do with the fact that the dependent variables are a list (vector). Any thoughts or suggestions would be appreciated. The sample data can be found here.


Solution

  • Wrap a capture.output() around it

    write(capture.output(summary(fit)), "fit.txt")
    

    You'll get a nice clean .txt file with everything shown in R console when you evaluate summary(fit). I do not recommend writing to .csv, but you if you insist, just use write.csv.

    And for your/future reader's reference, if you do decide to automate this process within a function, then you need to wrap a eval(..., envir = .GlobalEnv) to get rid of those annoying environment tags from being printed/written.