Reduce code with map

I have extracts that go into folders by year but want to consolidate them using purrr but getting stuck as seen below. I would like to reduce the imports to one function that use the folders_years and files vestors to create a list with 7 data frames.

Any idea how to do this?

path <- "G:/My Drive/qlikview_extracts/"
folders_years <- c("2016","2017","2018","2019")
folders_all <- "ALL"
files <- c("Answers.csv","ConsultationService.csv","Events.csv","Patients.csv","Paypoints.csv","Questions.csv","Services.csv")
names_ <- str_remove(files, ".csv")
read_csv_as_char <- partial(read_csv, col_types = cols(.default = col_character()))
import_file <- as_mapper(~paste(path, .x , .y, sep = "/"))
  
l <- map(files, list) %>% set_names(names_)

# Need help to reduce the code below to one function

l$Answers <- 
  folders_years %>% 
  map_df(~ read_csv_as_char(file = import_file(.x, "Answers.csv")))

l$ConsultationService <- 
  folders_years %>% 
  map_df(~ read_csv_as_char(file = import_file(.x, "ConsultationService.csv")))

l$Events <-
  folders_years %>% 
  map_df(~ read_csv_as_char(file = import_file(.x, "Events.csv")))

l$Patients <- 
  folders_years %>% 
  map_df(~ read_csv_as_char(file = import_file(.x, "Patients.csv")))

l$Paypoints <- 
  folders_years %>% 
  map_df(~ read_csv_as_char(file = import_file(.x, "Paypoints.csv")))

l$Questions <- 
  folders_years %>% 
  map_df(~ read_csv_as_char(file = import_file(.x, "Questions.csv")))

l$Services <- 
  folders_years %>% 
  map_df(~ read_csv_as_char(file = import_file(.x, "Services.csv")))

Creating a new function may help.

list_file <- function(y) {
  l[[y]] <<- folders_years %>% map_df(~ read_csv_as_char(file = import_file(.x, paste0(y, ".csv"))))
}

map(names_, list_file)
2 Likes

Thank you, worked perfectly.

What a great community to be part of!!!!!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.