在 R 中创建 .txt 文件

creating .txt file in R

for (i in 3:52){
cat(" ID,NAME,LAT,LONG,ELEVATION
1,25_i_PCP,39.269,-92.127,261.000
2,32_i_PCP,39.241,-92.160,263.000
3,34_i_PCP,39.223,-92.141,264.000
4,38_i_PCP,39.298,-92.083,243.000
5,201_i_PCP,39.228,-92.119,263.000
    ",file="pcpfork_i.txt",sep="\n",append=TRUE)}"

我想通过将 i 从 3 替换为 52,使用 for 循环创建 50 个不同的 .txt 文件。

这里有几个选项。首先,请注意。在对 cat() 的调用中不需要 append = TRUEsep = "\n",因为没有要追加或分离的内容。这些都在单独的文件中。

选项 1: 在您的文本中,您可以将 i 替换为 %d,调用 tmp,然后 运行 它通过 sprintf() 的循环。

tmp <- "ID,NAME,LAT,LONG,ELEVATION
1,25_%d_PCP,39.269,-92.127,261.000
2,32_%d_PCP,39.241,-92.160,263.000
3,34_%d_PCP,39.223,-92.141,264.000
4,38_%d_PCP,39.298,-92.083,243.000
5,201_%d_PCP,39.228,-92.119,263.000"

for (i in 3:52) {
    cat(
        do.call(sprintf, c(tmp, as.list(rep(i, 5)))), 
        file = sprintf("pcpfork_%d.txt", i)
    )
}

方案二:保留原文,替换为gsub()

tmp <- "ID,NAME,LAT,LONG,ELEVATION
1,25_i_PCP,39.269,-92.127,261.000
2,32_i_PCP,39.241,-92.160,263.000
3,34_i_PCP,39.223,-92.141,264.000
4,38_i_PCP,39.298,-92.083,243.000
5,201_i_PCP,39.228,-92.119,263.000"

for (i in 3:52) {
    cat(
        gsub("_i_", paste0("_", i, "_"), tmp, fixed = TRUE),
        file = sprintf("pcpfork_%d.txt", i)
    )
}

这些应该会让你朝着正确的方向前进。