23
votes

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
I'd suggest trying write.csv(as.data.frame(summary(regression1)$coef), file="regression1.csv)Roland
Thank you very much! It works. Just one thing left: every information is in different columns but always in one cell. How may I change that?OST_EE
It looks like this: [link]abload.de/image.php?img=screenshotmushj.jpg [/link] Would be great to separate the values to A2 B2 C2 D2 etc.OST_EE
Possibly you need to use write.csv2. Otherwise you need to take care to import the data correctly to Excel (e.g., specify the column seperator in Excel). That's not an R problem.Roland
For folks dealing with (not too large) sparse matrices, this may work: write.csv(as.data.frame(as.matrix(Y)), row.names = T, file ='F:/testY.csv') ...not pRetty...Quetzalcoatl

1 Answers

34
votes

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")