[英]How to save summary(lm) to a file?
我正在使用R進行葯效學分析,而且我對編程很新。
問題是,我正在進行線性回歸分析,將來我會執行更高級的方法。 因為我正在執行大量的分析(而且每次運行腳本時我都懶得手動復制粘貼),我想將分析的摘要保存到文件中。 我嘗試過不同的方法,但似乎沒什么用。
我正在尋找的是以下(最好)一個文本文件:
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
我已經搜索了將匯總函數保存到.csv或.txt的方法,但這些文件並不以我能理解的方式表示數據。
我試過的事情:
fileConn <- file("output.txt")
writeLines(sum1, fileConn)
close(fileConn)
返回:
Error in writeLines(sum1, fileConn) : invalid 'text' argument
嘗試使用write.table命令給出:
> 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
使用write命令:
> write(sum1, 'output.txt')
Error in cat(list(...), file, sep, fill, labels, append) : argument 1 (type 'list') cannot be handled by 'cat'
然后我越來越接近以下內容:
> write.table(sum1, 'output.csv', sep=",", row.names=FALSE, col.names=TRUE, quote=FALSE)
但是這個文件沒有與打印摘要相同的可讀信息
我希望有人可以提供幫助,因為這是我的高級編程方式。
我認為一個選項可能是sink()
,它會將結果輸出到文本文件而不是控制台。 在沒有您的數據集的情況下,我以cars
為例:
sink("lm.txt")
print(summary(lm(cars$speed ~ cars$dist)))
sink() # returns output to the console
lm.txt
現在看起來像這樣:
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對knitr
的建議更為復雜,但值得一提,因為你可以輕松地將輸入,文本輸出和數字編織到一個報告或html文件中。
上面的建議很有用。 根據您的需要,您可以對表的系數和glance()使用tidy()函數。
library( broom )
a <- lm(cars$speed ~ cars$dist)
write.csv( tidy( a ) , "coefs.csv" )
write.csv( glance( a ) , "an.csv" )
如果您想將數據重新導入R但仍希望將其存儲在文本文件中,還有輸入,例如,
dput(summary(lm(cars$speed~cars$dist)),file="summary_lm.txt",control="all")
這允許通過重新導入摘要對象
res=dget("summary_lm.txt")
我們來檢查一下res
的等級
class(res)
[1] "summary.lm"
試試apaStyle包:
library(apaStyle)
apa.regression(reg1, variables = NULL, number = "1", title = " title ",
filename = "APA Table1 regression.docx", note = NULL, landscape = FALSE, save = TRUE, type = "wide")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.