How to save summary(lm) to a file?

前端 未结 4 732
粉色の甜心
粉色の甜心 2020-12-24 02:47

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

相关标签:
4条回答
  • 2020-12-24 02:57

    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.

    0 讨论(0)
  • 2020-12-24 03:06

    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 讨论(0)
  • 2020-12-24 03:17

    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")
    
    0 讨论(0)
  • 2020-12-24 03:19

    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"
    
    0 讨论(0)
提交回复
热议问题