You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言for循环中动态修改输出文件名

Fixing Dynamic Filenames in R For Loops

The issue with your current code is that when you use "myfile[i].txt" as the filename, R treats it as a literal string—it doesn't replace i with the current loop number. To generate filenames like myfile1.txt, myfile2.txt, etc., you need to dynamically construct the filename using the loop variable i.

Here are two straightforward ways to fix this:

Method 1: Use paste0() to concatenate strings

paste0() is perfect for combining strings without extra spaces. We'll use it to glue together the prefix "myfile", the loop number i, and the suffix ".txt":

library("igraph")
dd <- read.table("afterFilter(48494).txt")
gg <- graph.data.frame(dd, directed=FALSE)
z <- scan("Active_Protein.txt", character(), sep = "\n")

for(i in 1:877) {
  x <- adjacent_vertices(gg, z[i])
  # Construct the filename dynamically
  filename <- paste0("myfile", i, ".txt")
  capture.output(x, file = filename)
}

Method 2: Use sprintf() for formatted strings

If you prefer a more structured way to format filenames (great for consistent numbering, like adding leading zeros if needed later), sprintf() is a solid choice. The %d acts as a placeholder for the integer value of i:

library("igraph")
dd <- read.table("afterFilter(48494).txt")
gg <- graph.data.frame(dd, directed=FALSE)
z <- scan("Active_Protein.txt", character(), sep = "\n")

for(i in 1:877) {
  x <- adjacent_vertices(gg, z[i])
  # Format the filename with the loop number
  filename <- sprintf("myfile%d.txt", i)
  capture.output(x, file = filename)
}

Both methods will generate unique filenames for each iteration of your loop, matching the value of i every time.

Bonus Tip

If you want to keep your output files organized, you can create a dedicated directory first and include it in the filename:

# Create output directory if it doesn't exist
if(!dir.exists("output_files")) {
  dir.create("output_files")
}

# Construct filename with the directory path
filename <- paste0("output_files/myfile", i, ".txt")

内容的提问来源于stack exchange,提问作者SUBHAMDATTA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:38:53