Read 100 Excel files at once
One Excel file for each month, each store or each school, and we copy the same read_excel() line 100 times. One short pipeline reads them all into one table, and remembers which file each row came from.
What we need
- R 4.1 or newer
- readxl, purrr and dplyr (writexl to make practice files)
- A folder of Excel files (we make three)
Make three practice files
We write three small files, one per month, into a folder named months.
library(writexl)
dir.create("months", showWarnings = FALSE)
for (m in 1:3) {
write_xlsx(
data.frame(day = 1:3, sales = m * c(10, 20, 30)),
sprintf("months/sales-%02d.xlsx", m)
)
}
list.files("months")Loading the checked output…
List the files
list.files() finds them. The pattern keeps only names ending in .xlsx, and full.names = TRUE keeps the folder in each name.
files <- list.files("months", pattern = "\\.xlsx$", full.names = TRUE)
filesLoading the checked output…
Read them all into one table
set_names() labels each file with its own name, map() reads each one, and list_rbind() stacks them, adding a column that says where each row came from.
library(readxl)
library(purrr)
all_sales <- files |>
set_names() |>
map(read_excel) |>
list_rbind(names_to = "file")
all_salesLoading the checked output…
Taste test
Count rows by file. Every file should be there, with the number of rows we expect.
library(dplyr)
count(all_sales, file)Loading the checked output…
Kitchen tip: the habit that prevents this
Always keep a column with the file name. When one number looks odd later, it tells us which file to open.
Three common mix-ups
- Excel's hidden lock files (names starting with ~$) get read too. Use pattern = "^[^~].*\\.xlsx$" to skip them.
- One file names a column "Sales" and another "sales", so they do not stack. Clean the names first.
- A column is numbers in one file and text in another. Set col_types in read_excel() so every file is read the same way.
Quick check
We read 12 monthly files and get 11 file names in count(). What is the first thing to check?
- list.files(pattern = ...)
- set_names() |> map(read_excel)
- list_rbind(names_to = "file")
- count(file) to check
Keep the recipe card
A one-picture summary to pin next to a screen or send to a friend who is stuck on the same thing.
Trying this on other data? Check the row counts and results before and after each step. Package versions change, so if something here works differently, please tell us. Every output on this page comes from running the code above in R; please cross-check before relying on it for our work.