如何将新行追加到列顺序不同的现有 csv 文件中

问题描述 投票:0回答:1

我有 4 个 csv 文件,每周我都会收到新的原始数据。我想将新数据附加到存储库中现有的 4 个 csv 文件报告中。问题是,当我使用带有参数“append = TRUE”的 write.table 或 write.csv 时,列不匹配,因此我的行被替换。

for (report in names(clean_reports)) {
  data <- clean_reports[[report]]
  write.table(data,
              file = paste(report,".csv",sep = ""),
              append = TRUE,
              col.names = FALSE,
              row.names = FALSE,
              sep = ",")
}

我期望根据列名称将列附加到正确的位置。显然 write.table 不会读取现有列。不确定还有什么其他解决方法

r csv append write.table
1个回答
1
投票

使用带有append = TRUE参数的write.table或write.csv时,不会根据列名称自动匹配列。相反,新数据只是简单地附加到现有文件中,而不考虑列结构。

要在确保列匹配的同时实现附加新数据的预期结果,您可以按照以下步骤操作:

将现有 CSV 文件读取到单独的数据框中。 将新数据附加到相应的数据框中。 将更新的数据帧写回 CSV 文件。

# List of file names
file_names <- c("report1.csv", "report2.csv", "report3.csv", "report4.csv")

# Read existing CSV files into data frames
existing_data <- lapply(file_names, read.csv)

# Loop through the reports and append new data
for (i in seq_along(file_names)) {
  report <- file_names[i]
  data <- clean_reports[[report]]  # Assuming clean_reports is a list with new data
  
  # Append new data to existing data frame
  if (exists(report, envir = .GlobalEnv)) {
    existing_data[[i]] <- rbind(existing_data[[i]], data)
  } else {
    existing_data[[i]] <- data
  }
  
  # Write the updated data frame back to the CSV file
  write.csv(existing_data[[i]], file = report, row.names = FALSE)
}

在此代码中,使用 read.csv 将现有 CSV 文件读入单独的数据帧。然后,对于每个报告,使用 rbind 将新数据附加到相应的现有数据帧。如果报表数据框尚不存在,则会使用新数据创建它。最后,使用 write.csv 将更新后的数据帧写回 CSV 文件,覆盖现有文件。

© www.soinside.com 2019 - 2024. All rights reserved.