将文本和数据框写入文件

5
什么是将文本和数据框写入文件的最佳方式?其中文本是通过将变量粘贴到字符串中创建的。
期望输出示例:
Here is some text.
This line has a variable: Hello World
Data frame below the line
=================
ID,val1,val2
1,2,3
2,4,6
3,6,9
4,8,12
5,10,15
6,12,18
7,14,21
8,16,24
9,18,27
10,20,30

我可以创建一个包含初始文本的字符串:
myvar <- "Hello World"
out_string <- paste0("Here is some text.\n",
                     "This line has a variable: ", myvar, "\n",
                     "Data frame below the line\n",
                     "=================\n")
cat(out_string)

我可以将数据框写入文件:

library(data.table)

mydf <- data.frame(ID = 1:10, val1 = 1:10*2, val2 = 1:10*3)

fwrite(x = mydf,
   file = "path/file.txt",
   sep = ",",
   col.names=T)

但我不确定如何最好地将这两者组合起来。

我认为将数据框粘贴到out_string的末尾,然后将其写入文件可能是最好的方法,但我的尝试失败了,例如:

cat(paste0(out_string, mydf, collapse=''))
# Here is some text.
# This line has a variable: Hello World
# Data frame below the line
# =================
#   1:10Here is some text.
# This line has a variable: Hello World
# Data frame below the line
# =================
#   c(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)Here is some text.
# This line has a variable: Hello World
# Data frame below the line
# =================
#   c(3, 6, 9, 12, 15, 18, 21, 24, 27, 30)
3个回答

6

可能有几种方法可以做到这一点。 其中一种简单的方法是

cat(out_string, file = '/tmp/test.txt')
cat(paste0(colnames(mydf), collapse = ','), file = '/tmp/test.txt', append = T, sep = '\n')
cat(apply(mydf,1,paste0, collapse=','), file = '/tmp/test.txt', append = T, sep = '\n')

当然,也可以使用fwrite函数:

cat(out_string, file = '/tmp/test.txt')
fwrite(x = mydf,
   file = "/tmp/test.txt",
   sep = ",",
   col.names=T,
   append=T)

这两种方法都按要求工作了。谢谢! - conor

2

一种选择是建立连接,您可以使用writeLineswrite.csv同时向其写入:

myvar <- "Hello World"
out_string <- paste0("Here is some text.\n",
                     "This line has a variable: ", myvar, "\n",
                     "Data frame below the line\n",
                     "=================\n")
mydf <- data.frame(ID = 1:10, val1 = 1:10*2, val2 = 1:10*3)


my_file <- file('file.csv', 'w')

writeLines(out_string, my_file, sep = '')
write.csv(mydf, my_file, quote = FALSE, row.names = FALSE)

close(my_file)

readLines('file.csv')
#>  [1] "Here is some text."                   
#>  [2] "This line has a variable: Hello World"
#>  [3] "Data frame below the line"            
#>  [4] "================="                    
#>  [5] "ID,val1,val2"                         
#>  [6] "1,2,3"                                
#>  [7] "2,4,6"                                
#>  [8] "3,6,9"                                
#>  [9] "4,8,12"                               
#> [10] "5,10,15"                              
#> [11] "6,12,18"                              
#> [12] "7,14,21"                              
#> [13] "8,16,24"                              
#> [14] "9,18,27"                              
#> [15] "10,20,30"

这个方法在out_stringmydf写入之间添加了一行,并且在输出列名时加上了引号。 - conor
@conor 更新后,删除了 writeLines 插入的分隔符(out_string 已经有了它们),并在 write.csv 中添加了 quote = FALSE 参数。我倾向于使用 readr::write_csv 来获得更好的默认值,但将其全部保留在基本 R 中也很好。 - alistaire
谢谢@alistaire,现在符合要求了。 - conor

2
另一种方法: sink()将打开一个文件连接。
sink("<your_new_file_name>")
out_string
df
sink()

这里应该有 cat(out_string) 才能正确渲染。除此之外,它几乎按照要求工作,但 mydf 的输出列是通过空格对齐的,而不是 CSV。如果需要这种格式,仍然很好用。 - conor
抱歉,我没有注意到你回答的格式细节。我以为你在问如何简单地编写一个将两个输出合并的文件。 - shea
没关系。我之前不知道 sink,现在看来它非常有用,所以感谢你的回答。 - conor

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