How to export coefficients of the regression analysis fto a spreadsheet or csv file?

这一生的挚爱 提交于 2019-12-03 06:59:26

问题


I am new to RStudio and I guess my question is pretty easy to solve but a lot of searching did not help me.

I am running a regression and summary(regression1) shows me all the coefficients and so on. Now I am using coef(regression1) so it only gives me the coefficients which I want to export to a file.

write.csv(coef, file="regression1.csv) and the "Error in as.data.frame.default(x[[i]], optional = TRUE) : cannot coerce class ""function"" to a data.frame" occurs.

Would be great If you could help me. I am searching the web for a few hours now and was not successful.

Do I have to change coef somehow so it fits in a data.frame?

Thank you very much!


回答1:


There's a contributed package called broom that simplifies this task, it converts model output to tidy dataframes. Here's a self-contained reproducible example:

Download and install the package:

library(devtools)
install_github("dgrtwo/broom")
library(broom)

Here's the normal base output, not very convenient:

lmfit <- lm(mpg ~ wt, mtcars)
lmfit

Call:
lm(formula = mpg ~ wt, data = mtcars)

Coefficients:
(Intercept)           wt  
     37.285       -5.344 

Here's the same model output after it's been tidied up by the broom package, much nicer and easier to work with:

tidy_lmfit <- tidy(lmfit)
tidy_lmfit
         term  estimate std.error statistic      p.value
1 (Intercept) 37.285126  1.877627 19.857575 8.241799e-19
2          wt -5.344472  0.559101 -9.559044 1.293959e-10

And here's how you'd write that dataframe to CSV:

write.csv(tidy_lmfit, "tidy_lmfit.csv")


来源:https://stackoverflow.com/questions/26866839/how-to-export-coefficients-of-the-regression-analysis-fto-a-spreadsheet-or-csv-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!