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

前端 未结 6 2125
轮回少年
轮回少年 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 20:59

    You could use purrr::map2 here, which works similarly to mapply

    filenames <- list.files(path, full.names = TRUE, pattern = fileptrn, recursive = TRUE)
    sites <- str_extract(filenames, "[A-Z]{2}-[A-Za-z0-9]{3}")  # same length as filenames
    
    library(purrr)
    library(dplyr)
    library(readr)
    stopifnot(length(filenames)==length(sites))  # returns error if not the same length
    ans <- map2(filenames, sites, ~read_csv(.x) %>% mutate(id = .y))  # .x is element in filenames, and .y is element in sites
    

    The output of map2 is a list, similar to lapply

    If you have a development version of purrr, you can use imap, which is a wrapper for map2 with an index

提交回复
热议问题