This is a tricky dplyr & purrr question I want to simplify the following code into one dplyr pipe:
filenames <- list.files(path = data.location, pattern = "*.csv") %>%
map_chr(function(name) gsub(paste0('(.*).csv'), '\\1', name))
files.raw <- list.files(path = data.location, pattern = "*.csv", full.names = TRUE) %>%
map(read_csv) %>%
setNames(filenames)
I tried to do this solution but it failed because the filenames must be used with full path (full.names = TRUE) for read_csv() but I want to assign the filenames without the full path.
In other words, this worked - but only with full path in filenames:
list.files(path = data.location, pattern = "*.csv", full.names = TRUE) %>%
{ . ->> filenames } %>%
map(read_csv) %>%
setNames(filenames)
but this didn't:
list.files(path = data.location, pattern = "*.csv", full.names = TRUE) %>%
{ map_chr(., function(name) gsub(paste0(data.location, '/(.*).csv'), '\\1', name)) ->> filenames } %>%
map(read_csv) %>%
setNames(filenames)
Is there a way to make the map_chr work with the save (->> filenames
), or is there an even simpler way to completely avoid saving to a temporary variable (filenames)?