什么是将文本和数据框写入文件的最佳方式?其中文本是通过将变量粘贴到字符串中创建的。
期望输出示例:
我可以创建一个包含初始文本的字符串:
期望输出示例:
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)