R语言写入CSV文件时追加操作失效问题求助
Hey there! I see the problem—your current script is overwriting the CSV file every time the loop runs instead of appending new data. That's because write.csv() defaults to append = FALSE, which replaces the file each time. Plus, even if you set append = TRUE, it would write the header row every iteration, which isn't what you want. Let's fix this with two solid solutions:
Solution 1: Append Iteratively (With Controlled Headers)
We'll write the header only once on the first iteration, then append subsequent data without headers using write.table() (it's more flexible than write.csv() for this use case):
target <- c("Autocorrelation","InformationContent_zero","InformationContent_one","InformationContent_two", "InformationContent_four","PartialIC_zero","PartialIC_one","PartialIC_two","PartialIC_four", "DBI_zero","DBI_one","DBI_two","DBI_four") output_path <- "/home/nasser/Desktop/Experiments/your_final_output.csv" for (idx in seq_along(target)) { tar <- target[idx] # Your existing data processing steps AC_data <- subset(data, select = c(tar)) AC <- aggregate(AC_data, list(class = data$TARGET_CLASS), mean) ordered_AC <- AC[order(-AC[[tar]]),] # First iteration: write full data with header if (idx == 1) { write.csv(ordered_AC, file = output_path, row.names = FALSE) } else { # Subsequent iterations: append without header, match CSV format write.table(ordered_AC, file = output_path, sep = ",", append = TRUE, row.names = FALSE, col.names = FALSE) } }
Why this works:
write.table()lets us togglecol.names = FALSEfor appends, so we don't duplicate headers.- We keep
row.names = FALSEconsistent to avoid adding an extra index column to your CSV.
Solution 2: Collect All Data First, Write Once (More Efficient)
If your dataset isn't massive, it's better to gather all results in a list first, then combine and write in one go. This reduces disk I/O and keeps your data structured clearly:
target <- c("Autocorrelation","InformationContent_zero","InformationContent_one","InformationContent_two", "InformationContent_four","PartialIC_zero","PartialIC_one","PartialIC_two","PartialIC_four", "DBI_zero","DBI_one","DBI_two","DBI_four") result_list <- list() for (tar in target) { AC_data <- subset(data, select = c(tar)) AC <- aggregate(AC_data, list(class = data$TARGET_CLASS), mean) ordered_AC <- AC[order(-AC[[tar]]),] # Add a column to track which metric this result belongs to ordered_AC$metric <- tar result_list[[tar]] <- ordered_AC } # Combine all results into a single data frame combined_results <- do.call(rbind, result_list) # Write the full dataset once write.csv(combined_results, file = "/home/nasser/Desktop/Experiments/your_final_output.csv", row.names = FALSE)
Bonus benefit:
The added metric column makes it easy to distinguish which rows correspond to each of your target variables later on.
Pick the solution that fits your workflow—either will solve your append issue!
内容的提问来源于stack exchange,提问作者Adam Amin

