35

I'm using R for a pharmacodynamic analysis and I'm fairly new to programming.

The thing is, I'm carrying out linear regression analysis and in the future I will perform more advanced methods. Because I'm performing a large number of analysis (and I'm too lazy to manually copy paste every time I run the script), I would like to save the summaries of the analysis to a file. I've tried different methods, but nothing seems to work.

What I'm looking for is the following as (preferably) a text file:

X_Y <- lm(X ~ Y)
sum1 <- summary(X_Y)

> sum1

Call:
lm(formula = AUC_cumulative ~ LVEF)

Residuals:
    Min      1Q  Median      3Q     Max 
-910.59 -434.11  -89.17  349.39 2836.81 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept) 1496.4215   396.5186   3.774 0.000268 ***
LVEF           0.8243     7.3265   0.113 0.910640    
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 619.9 on 104 degrees of freedom
  (32 observations deleted due to missingness)
Multiple R-squared:  0.0001217, Adjusted R-squared:  -0.009493 
F-statistic: 0.01266 on 1 and 104 DF,  p-value: 0.9106

I've searched for methods to save summary functions to a .csv or .txt, but those files don't represent the data in a way I can understand it.

Things I've tried:

fileConn <- file("output.txt")
writeLines(sum1, fileConn)
close(fileConn)

This returns:

Error in writeLines(sum1, fileConn) : invalid 'text' argument

An attempt using the write.table command gave:

> write.table(Sum1, 'output.csv', sep=",", row.names=FALSE, col.names=TRUE, quote=FALSE)
Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = stringsAsFactors) : cannot coerce class ""summary.lm"" to a data.frame

Using the write command:

> write(sum1, 'output.txt')
Error in cat(list(...), file, sep, fill, labels, append) : argument 1 (type 'list') cannot be handled by 'cat'

Then I was getting closer with the following:

> write.table(sum1, 'output.csv', sep=",", row.names=FALSE, col.names=TRUE, quote=FALSE)

But this file did not have the same readable information as the printed summary

I hope someone can help, because this is way to advanced programming for me.

3
  • 2
    You could try ?capture.output ie. capture.output(sum1, 'output.txt')
    – akrun
    Commented May 21, 2015 at 10:51
  • 2
    I'd suggest to use knitr. That's really easy if you use RStudio.
    – Roland
    Commented May 21, 2015 at 11:04
  • 1
    You may check broom to convert "the messy output of built-in functions in R, such as lm [..] and turns them into tidy data frames".
    – Henrik
    Commented May 21, 2015 at 11:06

4 Answers 4

63

I think one option could be sink() which will output the results to a text file rather than the console. In the absence of your dataset I've used cars for an example:

sink("lm.txt")
print(summary(lm(cars$speed ~ cars$dist)))
sink()  # returns output to the console

lm.txt now looks like this:

Call:
lm(formula = cars$speed ~ cars$dist)

Residuals:
    Min      1Q  Median      3Q     Max 
-7.5293 -2.1550  0.3615  2.4377  6.4179 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  8.28391    0.87438   9.474 1.44e-12 ***
cars$dist    0.16557    0.01749   9.464 1.49e-12 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 3.156 on 48 degrees of freedom
Multiple R-squared:  0.6511,    Adjusted R-squared:  0.6438 
F-statistic: 89.57 on 1 and 48 DF,  p-value: 1.49e-12

@Roland 's suggestion of knitr is a bit more involved, but could be worth it because you can knit input, text output, and figures in to one report or html file easily.

3
  • 1
    Always a pleasure. You should look in to knitr and broom though, as per previous commenter's suggestions: they're a bit more involved but more sophisticated than sink. Good luck
    – Phil
    Commented May 22, 2015 at 9:15
  • Hello, that is exactly the way i did, too. However, the apostrophs around the significance asterices (***) are presented decrypted in the txt file. Is there a way to solve that?
    – Rockbar
    Commented Jun 26, 2017 at 13:04
  • @Rockbar I'd start a new question, linking to this one. Try to post an example of what you mean; I don't know what you mean by decrypted?
    – Phil
    Commented Jun 26, 2017 at 13:51
10

The suggestion above work great. Depending what you need you can use the tidy() function for the coefficients and glance() for the table.

library( broom )
a <- lm(cars$speed ~ cars$dist)
write.csv( tidy( a ) , "coefs.csv" )
write.csv( glance( a ) , "an.csv" )
0
6

Should you want to re-import the data into R but still want to have it in a text file, there is also dput, e.g.,

dput(summary(lm(cars$speed~cars$dist)),file="summary_lm.txt",control="all")

This allows to re-import the summary object via

res=dget("summary_lm.txt")

Let's check the class of res

class(res)
[1] "summary.lm"
-1

try apaStyle package:

library(apaStyle)
apa.regression(reg1, variables = NULL, number = "1", title = " title ",
               filename = "APA Table1 regression.docx", note = NULL, landscape = FALSE, save = TRUE, type = "wide")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.