gpt4 book ai didi

command-line - R - 将 R 输出的元素捕获到文本文件中

转载 作者:行者123 更新时间:2023-12-03 01:13:56 25 4
gpt4 key购买 nike

我尝试通过命令行调用 R 来运行分析,如下所示:

R --no-save < SampleProgram.R > SampleProgram.opt

例如,考虑下面的简单 R 程序:

mydata = read.csv("test.txt", header=T)
attach(mydata)
summary(Variable1)
q()

输出显示在 SampleProgram.opt 中(仅部分显示):

> mydata = read.csv("test.txt", header=T)
> attach(mydata)
> summary(Variable1)
Min. 1st Qu. Median Mean 3rd Qu. Max.
1.00 1.00 2.00 2.47 3.00 4.00
> q()

这个简单的 R 程序将由需要使用为 Variable1 显示的摘要统计信息的脚本执行。

问题是:R中有没有办法捕获summary(Variable1)的输出并将结果写入输出文件?换句话说,我需要 R 运行 Variable1 的汇总统计,捕获“Min”、“Median”和“Max”值,并将这些值单独写入输出文本文件。在此示例中,输出文件应仅包含一行,其值为“1.00、2.00、4.00”(即“最小值”、“中值”和“最大值”)。

上面的例子讨论了汇总函数。但是,我还需要使用其他命令(例如 glm)来执行此操作

我对 R 相当陌生,想知道 R 中是否有办法可以做到这一点?

感谢您的帮助。

最佳答案

一个简单的方法是将要打印的输出转换为文件,并通过 capture.output 将其转换为文本字符串。然后你可以简单地将输出cat到文件中。

dat<-data.frame(a=rnorm(100),b=rnorm(100),c=rnorm(100))
mod<-lm(a~b+c,data=dat)
out<-capture.output(summary(mod))
cat(out,file="out.txt",sep="\n",append=TRUE)
out<-capture.output(vcov(mod))
cat(out,file="out.txt",sep="\n",append=TRUE)

这将创建一个文件 out.txt,其中包含

Call:
lm(formula = a ~ b + c, data = dat)

Residuals:
Min 1Q Median 3Q Max
-2.67116 -0.81736 -0.07006 0.76551 2.91055

Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.01196 0.11724 0.102 0.919
b 0.11931 0.12601 0.947 0.346
c -0.09085 0.13267 -0.685 0.495

Residual standard error: 1.171 on 97 degrees of freedom
Multiple R-squared: 0.0183, Adjusted R-squared: -0.001944
F-statistic: 0.9039 on 2 and 97 DF, p-value: 0.4084

(Intercept) b c
(Intercept) 0.0137444761 -0.0006929722 -0.0005721338
b -0.0006929722 0.0158784141 0.0042188705
c -0.0005721338 0.0042188705 0.0176018744

关于command-line - R - 将 R 输出的元素捕获到文本文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1734896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com