使用cat命令写入data.frame数据框

8

我如何将数据框abc添加/附加到之前打开的文本文件中。 我正在向该文件写入一些重要信息,然后我想在该信息下附加该数据框。 当我尝试使用cat写入数据框abc时,我会遇到错误。

fileConn<-file("metadata.txt","w+")
smoke <- matrix(c(51,43,22,92,28,21,68,22,9),ncol=3,byrow=TRUE)
smoke <- as.data.frame(smoke)
table <- sapply (smoke, class)
abc <- data.frame(nm = names(smoke), cl = sapply(unname(smoke), class))
cat("some imp info","\n", file=fileConn)
cat(abc,"\n", file=fileConn)
close(fileConn)
class(abc)

3
capture.output(abc, file = fileConn) 也可以起到同样的作用。 - lukeA
@lukeA,它有效。请将其添加为答案,我会接受它。 - user2543622
3个回答

4

只需使用编写 data.frame 的标准工具,即 write.table:

write.table(abc, 'yourfile', append=TRUE) # plus whatever additional params

2

试试这个

capture.output(abc, file = fileConn)

1
为了确保输出的可读性,您也可以使用 knitr::kable()。它会将表格打印为字符形式,这样您就可以直接在 cat() 调用中嵌入它,这样更加方便。它还有一些打印选项(digitsalignrow.names 等),可以轻松控制您的表格打印效果:
tab <- knitr::kable(head(swiss))

cat("This is my file:",
    "Some important note about it",
    tab,
    sep="\n")
#> This is my file:
#> Some important note about it
#> |             | Fertility| Agriculture| Examination| Education| Catholic| Infant.Mortality|
#> |:------------|---------:|-----------:|-----------:|---------:|--------:|----------------:|
#> |Courtelary   |      80.2|        17.0|          15|        12|     9.96|             22.2|
#> |Delemont     |      83.1|        45.1|           6|         9|    84.84|             22.2|
#> |Franches-Mnt |      92.5|        39.7|           5|         5|    93.40|             20.2|
#> |Moutier      |      85.8|        36.5|          12|         7|    33.77|             20.3|
#> |Neuveville   |      76.9|        43.5|          17|        15|     5.16|             20.6|
#> |Porrentruy   |      76.1|        35.3|           9|         7|    90.57|             26.6|

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接