如何在每个csv文件中添加列,列的值取决于csv的名称

时间:2019-10-11 03:15:56

标签: r

我有50个文件夹。在每个文件夹中,我有四个名称为xx_14,xx_15,xx_16,xx_17的数据集。数字表示年份。对于每个文件夹,我需要将四个数据集合并在一起。

我还需要在合并的数据集中为每个文件夹创建一个新列,其中该列下的值为与这四个数据集的年份相对应的年份(时间段)。

我不能只在R中手动进行操作,因为我有50个文件夹,每个文件夹都包含4种数据集,因此我需要为这50个文件夹创建一个for循环。无论是哪个文件夹,csv文件始终采用xx_14或15或16或17的形式。

1 个答案:

答案 0 :(得分:0)

尝试这种基本的R方法:

#Get list of all 50 folders
all_folders <- dir("/path/to/outer/folder", full.names = TRUE)

#Loop over each folder
lapply(all_folders, function(x)  {
   #Get all the filenames in that folder
   file_path <- list.files(x, full.names = TRUE)
   #Read all the files and rbind them
   do.call(rbind, lapply(file_path, function(x) 
           #Add a new column with name of the filename
           transform(read.csv(x), year = sub("\\.csv$", "", basename(x)))))
})