Combine CSV files in R
How to read several CSV files in R and stack them into one table with base R, readr or data.table, plus the schema, type and encoding checks that keep the result usable.
Combining CSV files in R usually means reading a folder of files that share a structure and stacking their rows into one data frame. It is one of the most common delimited-text tasks, and R handles it well. Whether the result is trustworthy depends less on which function you pick and more on whether the files really share column names, types and encoding. This review covers what combining changes, the main approaches, where meaning can be lost, and how to check the output before you share it.
Is combining in R the right choice?
For recurring work, or for more than a handful of files, combining in R is a sound choice. The main benefit is reproducibility. A short script records exactly which files were read, how columns were typed and how mismatches were handled, so you can rerun it when new files arrive. The decisive tradeoff is that R will only produce a meaningful table if the files are structurally consistent. If they are not, it will either stop with an error or quietly fill gaps with missing values. You have to decide which outcome you want and check for it.
Plain-text handling or keeping the files separate is preferable in a few cases. One is a one-off merge of two small files with identical headers. Another is when the recipient needs the original files intact for audit or provenance. A third is when the files differ so much in structure that forcing them into one table would misrepresent the data. In that last case, a join on a shared key or a cleanup step comes before any stacking.
What combining actually changes
The word "combine" covers three different operations, and it helps to be clear which one you mean:
- Row binding (stacking): files with the same columns are appended one under another. This is what most people searching for this task want, and it is the focus here.
- Joining (merging): files with different columns are matched row by row on a shared key, such as an ID. In R this is done with merge() or the dplyr join functions, not with row binding.
- Raw text concatenation: the file contents are pasted end to end outside of R's data model. This repeats the header line once per file and does not reconcile column order, so it is rarely what you want for CSV.
When R stacks files, each file is first parsed into a data frame. The header rows become column names and are not duplicated in the output. Cell values are stored as R values, such as numbers, text, logicals or dates, rather than as the original characters. That parsing step is where changes can happen. A column that looked like "00742" in the file can become the number 742 if R guesses a numeric type. If one file stores a column as text and another as numbers, the functions behave differently: some coerce the column to a common type and some refuse to combine.
Column matching also differs between functions. Base R's rbind() for data frames matches columns by name and stops with an error if the sets of names differ. dplyr::bind_rows() matches by name and fills columns that are missing from some files with NA. data.table::rbindlist() can match by name with use.names = TRUE and fill gaps with fill = TRUE. Each of these is reasonable, but they give different results on the same messy input.
Reading several CSV files at once
Every approach starts with a vector of file paths. list.files() with a pattern and full.names = TRUE is the usual way to collect them. Here are three common patterns. The folder name "data" is a placeholder.
Base R needs no packages. It works well when all files have identical column names:
files <- list.files("data", pattern = "\\.csv$", full.names = TRUE)
dfs <- lapply(files, read.csv)
dfs <- Map(function(df, f) { df$source_file <- basename(f); df }, dfs, files)
combined <- do.call(rbind, dfs)
readr (version 2.0 and later) accepts a vector of paths directly. It can record which file each row came from:
library(readr)
files <- list.files("data", pattern = "\\.csv$", full.names = TRUE)
combined <- read_csv(files, id = "source_file")
data.table reads each file with fread() and stacks the results with rbindlist(). The fill and idcol arguments handle missing columns and record the source:
library(data.table)
files <- list.files("data", pattern = "\\.csv$", full.names = TRUE)
files <- setNames(files, basename(files))
combined <- rbindlist(lapply(files, fread), use.names = TRUE, fill = TRUE, idcol = "source_file")
If you already use the tidyverse, a common alternative is to read the files with lapply() or purrr::map() and combine them with dplyr::bind_rows(). In current purrr releases, map_dfr() is superseded in favor of map() followed by list_rbind(). It still works, but newer code tends to use the replacement.
| Approach | Mismatched column names | Records source file | Type handling |
| Base R: lapply + read.csv + do.call(rbind) | Stops with an error | Only if you add a column yourself | Each file typed separately; mismatches may coerce or fail |
| readr::read_csv(files) | Expects a consistent structure; set col_types to be safe | Yes, via id | One column specification applied across files |
| dplyr::bind_rows on a list | Fills missing columns with NA | Yes, via .id on a named list | Errors on incompatible types, such as text versus numbers |
| data.table::rbindlist | Fills with NA when fill = TRUE | Yes, via idcol | Coerces to a common type where possible |
The table describes documented behavior in general terms. Details can change between package versions, so check the help page for the version you have installed. No speed measurements were supplied for this review. data.table and readr are often chosen for large files, but this review makes no claims about relative performance.
Where a combined table can lose meaning
- Leading zeros: ZIP codes, account numbers and product codes can lose leading zeros if read as numbers. Declare them as character. In readr use col_types; in read.csv use colClasses; in fread use colClasses.
- Inconsistent types: one file with a stray text value in a numeric column can turn the whole combined column into text, or cause an error, depending on the function.
- Silent NA filling: functions that fill missing columns will not tell you that a column was misspelled in one file. Two near-duplicate columns with mostly empty values are a typical sign.
- Dates: files exported from different systems may use different date formats. Parse them explicitly instead of relying on guessing.
- Encoding: files saved in different encodings can produce garbled accented characters. read.csv accepts fileEncoding, readr uses locale(encoding = ...), and fread has an encoding argument.
- Regional formats: files that use semicolons as separators and commas as decimal marks need read.csv2 or readr::read_csv2. Otherwise numbers will be misread.
CSV and TSV files
Tab-separated files follow the same workflow with a different reader. Use read.delim() in base R, read_tsv() in readr, or fread(), which detects the separator automatically. If a folder mixes comma- and tab-separated files, read each group with the matching function and combine afterward. Check the column specifications are aligned before you combine. Tabs rarely appear inside values, which can make TSV files easier to parse. CSV relies on quoting to protect commas within fields, so a file with inconsistent quoting is a common source of shifted columns.
Will the combined file stay usable after sharing?
Once combined, the data usually goes back out as a CSV, and the export step has its own pitfalls. write.csv() adds a column of row names by default, which shows up as an unnamed extra column. Pass row.names = FALSE to avoid it. readr::write_csv() writes UTF-8 without row names. readr also documents write_excel_csv(), which adds a byte order mark so that Excel recognizes the file as UTF-8. data.table::fwrite() has a bom argument for the same purpose.
Opening a CSV in a spreadsheet application is a form of re-parsing, and spreadsheets may apply their own type guesses. They can strip leading zeros or reformat values that look like dates. This review includes no tested results for specific spreadsheet versions. If the recipient will work in a spreadsheet, test with a sample file in their application, or share a format that preserves types.
CSV is plain text, so copying and pasting it does not introduce hidden formatting. Pasting into a word processor or chat tool, however, may collapse the delimiters into an unreadable run of text. For people using screen readers, access depends on the application that opens the file. Spreadsheet software typically exposes cells and headers, while a raw text view reads values in sequence. No assistive technology testing was supplied for this review. If accessibility matters, use clear column headers and a short plain-language summary of what the file contains, and avoid relying on visual layout.
Keep the source-file column in the shared output unless there is a reason to drop it. It lets a reader trace any row back to its origin, which is often the only way to resolve a questionable value later.
Checks before you trust the result
- The combined row count equals the sum of the individual file row counts.
- The column names are the set you expected, with no near-duplicates created by spelling differences.
- Each column has the intended type, especially identifiers, dates and money values.
- The NA count per column has not jumped unexpectedly after combining.
- A few rows from each source file match the original values.
counts <- vapply(files, function(f) nrow(read.csv(f)), integer(1))
stopifnot(nrow(combined) == sum(counts))
names(combined)
str(combined)
colSums(is.na(combined))
The row-count check rereads every file, which is fine for modest data. For large folders, record the counts during the initial read instead.
Gaps in this review
This overview is based on the documented behavior of base R, readr, dplyr and data.table, and on general CSV principles. No benchmark figures, version-specific tests or destination-application tests were supplied. Statements about speed, about exact behavior in a particular package release, or about how a specific spreadsheet or screen reader handles the output should be checked against current documentation or a small test of your own.