Paul Rougieux
Paul Rougieux

Reputation: 11379

How to read multiple csv files into a single data frame in R?

How to read multiple csv files into a single data frame in R?

Similar questions have been asked here:

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.

Upvotes: 2

Views: 1043

Answers (1)

Paul Rougieux
Paul Rougieux

Reputation: 11379

To read many csv files into one data frame:

  1. Lists files with their full path.
  2. Apply the read_csv function to each element of the vector of file paths and return a data frame created by row-binding.
iris_csv <- list.files(data_dir, full.names = TRUE) %>%
    map_dfr(read_csv)

Upvotes: 3

Related Questions