使用cat将str()的输出写入文件连接

时间:2018-04-06 18:06:42

标签: r file-io

我知道我可以使用sink()重定向控制台的输出。例如,我可以编写iris数据集的列描述:

data(iris)
sink('iris.txt')
writeLines('Description of Iris Dataset:')
cat(str(iris))
sink()

使用所需输出

生成文件iris.txt
Description of Iris Dataset:
'data.frame':   150 obs. of  5 variables:
 $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

我可以使用cat()做同样的事情吗?我试过了:

con <- file('iris.txt','w')
writeLines('Description of Iris Dataset:',con)
cat(str(iris),file=con,append=TRUE)
close(con)

但只有第一行写入文件。 str()默默无法写入。

?cat&gt;下我们发现的细节:

  

目前只处理原子矢量和名称   NULL和其他零长度对象(不产生输出)。   字符串按原样输出(与print.default不同)   转义不可打印的字符和反斜杠 - 使用encodeString if   你想用cat输出编码的字符串。其他类型的R对象   应该在被转换之前(例如,通过as.character或格式)   传给了猫。这包括以整数形式输出的因子   载体

在阅读完本文后,我尝试用str(iris)(无差异)和as.character()包裹format()(在第二行添加NULL)。

这可能看起来很挑剔,但我想避免sink()的原因是因为我想在写入文件之间写一些东西来控制,而打开和关闭接收器是一个额外的步骤。 / p>

1 个答案:

答案 0 :(得分:1)

您可以使用capture.output()str()的结果转换为简单的字符向量。

尝试:

cat(capture.output(str(iris)), file=con, append=TRUE, sep="\n")
相关问题