如何在R语言for循环中动态修改输出文件名
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

