简体   繁体   English

R如何将不同类型的变量打印到一个txt文件中

[英]R how to print different types of variables into one txt file

I have a lm model, a numeric vector from vif function, and some character variables. 我有一个lm模型,一个vif函数的数值向量和一些字符变量。

gvmodel<-gvlma(lmFit)
VIF<-sqrt(vif(lmFit))
Str1<-"Original R-square=".567"
Str2<-"Cross-validated R-Square=.123"

I would like to print content of all into one single txt file. 我想将所有内容打印到一个txt文件中。 I tried cat and capture.output . 我尝试过catcapture.output

cat(gvmodel,VIF,Str1, file="E:/.../text.txt")
capture.output(paste(gvmodel,VIF,...,sep=""),file="E:/.../text.txt")

Obviously this did not work. 显然这没有用。 Anyone how to print them into a single txt file? 任何人如何将它们打印到单个txt文件中? Thanks 谢谢

Sink() works. Sink()有效。 Sink a txt file path and name, run any command that produces text outputs and they will be captured in the txt file. 接收txt文件的路径和名称,运行产生文本输出的任何命令,它们将被捕获在txt文件中。 And finally sink() to close. 最后, sink()关闭。

 sink("E:/.../Sink.txt")
 gvmodel
 sqrt(vif(ModeName))
 sink()

In your code gvmodel<-gvlma(lmFit) produces gvlma object. 在您的代码中gvmodel<-gvlma(lmFit)产生gvlma对象。 It cannot be directly printed to .txt file as such. 不能直接将其直接打印到.txt文件。 You can transform it first to characters using as.character() option: 可以先使用as.character()选项将其转换为字符:

gvmodel<-gvlma(lmFit)
gvmodel <- as.character(gvmodel)

The result is printable for example with cat . 例如,结果可以用cat打印。 So if you put all this together: 因此,如果将所有这些放在一起:

gvmodel<-gvlma(lmFit)
gvmodel <- as.character(gvmodel)
VIF<-sqrt(vif(lmFit))
Str1<-"Original R-square=.567"
Str2<-"Cross-validated R-Square=.123" # NB the corrected quotation marks

cat(gvmodel,VIF,Str1, file="yourfile.txt",sep="\t")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM