0
votes

I would like to read in all of the *.csv files in a directory using purrr::map, and I just wanted to ask if there's a better way than what I'm doing, particularly if it's from the tidyverse or easier to read.

In particular, would you use file.path()? Is there a simpler way, or an easier to read way?

library(tidyverse)

csv_filenames <- list.files(path = "raw_data/")
dfs <- map(csv_filenames, ~read_csv(file.path("raw_data/", .)))
df <- bind_rows(dfs)
2
looks pretty simple to me, if all the .csv files have the same column structure, you can just use map_df() to get the data.frame output - EJJ

2 Answers

3
votes

You can have list.files return full paths, which can be fed directly to map. Combined with the map_df suggestion in the comments, I would do:

df <- list.files( path="raw_data", full.names=TRUE ) %>% 
  map_dfr( read_csv )     # _dfr to be explicit about *row* binding
1
votes

You could try this base R solution:

files <- list.files(path = "raw_data/",pattern='.csv')
#Data frame
DF <- do.call('rbind',lapply(files,read.csv))