How to read multiple csv files into a single data frame in R?
Similar questions have been asked here:
- Read multiple CSV files into separate data frames most answers use the
assign()
function to assign to many data frames. - How do I make a list of data frames? most answers add data frames to a list of data frames using
append(l, df)
orl[[i]]=df
.
Reproducible example
Write sample csv files to a temporary directory.
library(dplyr)
library(tidyr)
library(purrr)
library(purrrlyr)
library(readr)
data_dir <- file.path(tempdir(), "iris")
dir.create(data_dir)
iris %>%
# To keep the Species column in the output
# Create a new column that will be used as the grouping variable
mutate(species_group = Species) %>%
group_by(species_group) %>%
nest() %>%
# Apply the write.csv() function to each row of the nested data frame
by_row(~write.csv(.$data,
file = file.path(data_dir, paste0(.$species_group, ".csv")),
row.names = FALSE))
In this example, there are 3 .csv
files in the data_dir
. The question is how to read them all into a single data frame.