Import multiple .csv files with different name pattern as a different dataframe

Viewed 178

I have multiple CSV files with 4 common name patterns. I am using purrr::map to import all 4 groups as a 4 different dataframes. I have 10 csv files per name pattern. name patterns: DLL HH comp_XXX, SHH DD comp_XXX, OPL FG comp_XXX and SLL FG comp_XXX

I used this snippet 4 times to cycle through the files and bind them all together and get 4 dfs , DLL, SHH, OPL and SLL dataframe at the end ( separate call for each name)

Here an example for DLL HH comp *** name pattern

dll <- list.files(path = my_path, pattern = 'DLL HH comp', full.names=TRUE) %>%
  map(read_csv ) %>% 
  bind_rows()

I am wondering, is there any more efficient way to do it? without needing copy&paste? Let's say if I have 10 file/groups instead of only 4 group/name patterns

1 Answers

EDIT: you can try map.

library(tidyverse)

patterns <- c('pattern1', 'pattern2', 'pattern3')


lst <- patterns %>%
  map(
    ~list.files(path = my_path, pattern = .x, full.names=TRUE) %>%
      map(read_csv) %>% 
      bind_rows()
  )

names(lst) <- patterns
Related