Add “filename” column to table as multiple files are read and bound

前端 未结 6 2124
轮回少年
轮回少年 2020-11-27 20:54

I have numerous csv files in multiple directories that I want to read into a R tribble or data.table. I use \"list.files()\" with the recursive argument set to TRUE to creat

6条回答
  •  长情又很酷
    2020-11-27 21:03

    The tidyverse provides an eloquent solution. I like to use the full file-path as the filename (which can later be truncated, if desired).

    An example loading .csv files:

    library(tidyverse); library(fs)
    

    specify file path

    data_dir <- path("file/directory")
    data_list = fs::dir_ls(data_dir, regexp = "\\.csv$")
    

    read data

    my_data = data_list %>% 
      purrr::map_dfr(read_csv, .id = "source")
    

    rename variables

    my_data_renamed <- my_data %>% 
      dplyr::mutate(source = stringr::str_replace(source, "text-to-replace", "new-text"))
    #where source is the renamed file-source column      
    

提交回复
热议问题