Thursday, February 9, 2017

Export R Regression outputs to Word or CSV

If you have every thought about exporting your Regression output to else where from R, copy and paste is not a smart way to do when you have repeat it. The good idea is to export the output to a file, txt or word file. 
Here I demonstrate the way to export to word file, where the structure remains intact. I demonstrate only with GLM and anova as an example, it should work with other methods too.
Data<- data.frame(y=c(3,2,3,4,5, 9,3,10,1,3, 5), 
                  x=c(41,32,39,40,37, 43,45,44,37,48, 19),
                  v=c("y", "n", "n", "y", "n", "y", "y", "n", "y", "n",  "y"))
Let's prepare some demo GLM models and do anova test.

M.glm1<- glm(y~x*v, data=Data)
M.glm2<- glm(y~x+v, data=Data)
M.glm3<- glm(y~x, data=Data)
A.an<-  anova(M.glm1, M.glm2, M.glm3)
Extract the GLM Summary and convert to a Data Frame. If the dataframe does not work with other types of outputs, try with “list”.
Result of more than one model can be combined on same output file. 
Let's insert Title Text in between each model summary outputs. This is not necessary if you export single or few models. This step will be helpful when  you combine many model outputs. 

T1<- c("Summary of Model 1")
T2<- c("Summary of Model 2")
T3<- c("Summary of Model 3")
T4<- c("Summary Model Comparison")
Now lets combine the results into single object with titles. The summary title can be defined as paste or print. Later function can turn off the quote. 
combind.Summary <- capture.output(print(T1, quote=F), summary(M.glm1), 
                                  paste(T2), summary(M.glm2), 
                                  paste(T3), summary(M.glm3), 
                                  paste(T4), A.an)
Let's convert to data frame before export 

out.ls<- data.frame(combind.Summary)

Export the Data Frame to MS Word file.

write.table(out.ls, "........./My results.doc", row.names = F, quote=FALSE)

If you wish for only the coefficient table of regression summary, it can be exported to a table as CSV. The following will help to do so. First extract the summary to an object, then take coefficient of the summary, which is the table part of the regression summary output. The export it to CSV file. Or if you have more than single model, the results can be combined to single table. 

summary(M.glm1)->SM1
summary(M.glm2)->SM2
summary(M.glm3)->SM3
Coef.SM <- rbind(m1=SM1$coefficients,"",  m2=SM2$coefficients, "", SM3$coefficients)
The blank quote will leave a row gap in CSV table

write.csv(Coef.SM, "......./My Result.csv")

This method should work in outputs other than regression, but not tested. 

Good Luck


No comments:

Post a Comment