簡體   English   中英

R 重命名許多 CSV 中的列

[英]R rename columns in many CSVs

我有 200 個具有相同兩列(日期和級別)的 csv。 但是,這些列目前沒有名稱。 對於我在 R 中使用的包,它們都需要具有相同的列名。有沒有辦法遍歷所有 CSV 並為它們提供所有列名(相同的列名、日期和級別)? 我是 R 新手,沒有太多編寫循環的經驗。

例如,目前每個 CSV 中的數據如下所示:

09/21/1299 | 23
09/22/1999 | 25
09/23/1999 | 25

但我希望它看起來像這樣:

date       | level
09/21/1299 | 23
09/22/1999 | 25
09/23/1999 | 25
  1. 使用list.files(path = "./", pattern = "*.csv))獲取所有 csv 文件的名稱
  2. 創建一個循環,您可以:
    • 讀入每個文件
    • 將列名分配給數據框或矩陣
    • 寫入新文件(或覆蓋原始文件)

在以下代碼中,請更改要分配給所有列的wanted_colnames 此代碼(如果需要修復)應該讀取文件夾files_folder所有 csv(將其更改為提供完整路徑)。 最后,您可以在dfs上使用rbind_fill / rbindlist來獲取完整的數據幀。

wanted_colnames <- c('var1', 'var2', 'var3')
files_folder <- '/files/folder/path'

docs <- list.files(files_folder)
dfs <- list()
for(doc in docs) {
   full_path <- file.path(files_folder, doc)
   dfs[doc] <- read.csv(full_path)
   names(dfs[doc]) <- wanted_colnames
}

要訪問你可以使用一個文件夾中的所有文件list.files ,那么你就可以閱讀他們每個人的read.csv ,最后,你應該把它們寫入新文件與write.csv

總體而言,您將擁有類似於以下內容的代碼:

files <- list.files("path/to/directory/")
sapply(files, function(file){
                      x <- read.csv(file)
                      colnames(x) <- c("Col1", "Col2")
                      write.csv(paste0("new_", file),x)
}

我假設您不只是想讀取文件,而是實際修改文件以使其包含列標題。

為了讓以下代碼工作,您需要定義兩個變量: path應指向存儲原始文件的文件夾。 out_path應該是文件夾的路徑,修改后的文件應該存儲在該文件夾中。 如果文件夾out_path不存在,則會創建它。

這段代碼讀取path所有 csv 文件,添加標題並將修改后的文件寫入文件夾out_path

# create the output folder
# showWarnings = FALSE ensures that the function does not complain,
# even if the folder already exists
dir.create(out_path, showWarnings = FALSE)

# get the names of the input files with their full path
files <- list.files(path, "\\.csv", full.name = TRUE)

# loop through all the input files
for (file in files) {

  # read the file, specify the correct separator
  data <- read.table(file, sep = "|")

  # set the column names
  names(data) <- c("date", "level")

  # define the output file name: the file should be written to
  # out_path and have the same name as the original file
  outfile <- file.path(out_path, basename(file))

  # write the file. You need to specify the separator (|), and
  # omit row names and quotes
  write.table(data, outfile, sep = "|", row.names = FALSE, quote = FALSE)
}

您問題中的示例文件將變成:

date|level
09/21/1299 |23
09/22/1999 |25
09/23/1999 |25

請注意,標題沒有很好地對齊。 如果文件被讀取為 csv 文件,這應該不是問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM