我试图遍历数据框以生成具有特定格式的文本文件。这是一个示例数据框:
x <- 1:10
y <- 10:1
df <- data.frame(x,y)
此循环将以我想要的格式打印文本:
for (n in 1 : length(df[,1]))
{
cat(paste("\n-insertblock weld\n", df[n,1], df[n,2], "\n1\n1\n0", sep = " "))
}
我现在想做两件事:1)将打印添加到txt文件2)在顶部添加更多文本(对于我生成的每个文件都是相同的)。我发现这个问题显示了如何将txt写入文件:
Write lines of text to a file in R
这一个(how to write to files with writeLines in R)告诉我writeLines
需要事情as.character
。这是我的尝试:
fileConn <- file("output.txt")
for (n in 1 : length(df[,1]))
{
writeLines(cat(paste("\n-insertblock weld\n", as.character(df[n,1])), as.character(df[n,2]), "\n1\n1\n0", sep = " "), fileConn)
}
close(fileConn)
然而,这会产生错误:
writeLines中的错误(cat(粘贴(&#34; \ n-insertblock weld \ n&#34;, as.character(df [n,:invalid&#39; text&#39; argument
如果我删除cat
错误消失但我只得到输出的最后一行:
for (n in 1 : length(df[,1]))
{
writeLines(paste("\n-insertblock weld\n", as.character(df[n,1]), as.character(df[n,2]), "\n1\n1\n0", sep = " "), fileConn)
}
close(fileConn)
-insertblock weld
10 1
1
1
0
创建正确的txt文件后,我需要将其添加到顶部:
--simplenote
J
C
-36.413,33.568
5
0
我用保存粘贴文本的方法咆哮错误的树吗?任何帮助表示赞赏
答案 0 :(得分:2)
sink("count.txt",split=FALSE,append = FALSE)
cat(paste("--simplenote\n","J\n","C\n","-36.413,33.568\n","5\n","0\n", sep = " "))
for (n in 1 : length(df[,1]))
{
cat(paste("\n-insertblock weld\n", df[n,1], df[n,2], "\n1\n1\n0", sep = " "))
}