How to Merge Multiple CSV Files in R (Step-by-Step Example)


You can use the following basic syntax to import and merge multiple CSV files located in the same folder into R:

df <- list.files(path='C:/my/path/to/files') %>% 
  lapply(read_csv) %>% 
  bind_rows

The following step-by-step example shows how to use this syntax in practice.

Step 1: Create & Export Multiple Data Frames

First, we’ll use the following code to create and export three data frames to CSV files:

#create three data frames
df1 <- data.frame(points=c(4, 5, 5, 6, 8, 9),
                  assists=c(3, 2, 4, 4, 6, 3))

df2 <- data.frame(points=c(2, 10, 14, 15),
                  assists=c(3, 2, 9, 3))

df3 <- data.frame(points=c(6, 8, 9),
                  assists=c(10, 6, 4))

#export all three data frames to CSV files
write.csv(df1, 'C:/Users/bob/Documents/my_data_files/df1.csv', row.names=FALSE)
write.csv(df2, 'C:/Users/bob/Documents/my_data_files/df2.csv', row.names=FALSE)
write.csv(df3, 'C:/Users/bob/Documents/my_data_files/df3.csv', row.names=FALSE)

I can navigate to this folder and see that the three CSV files were successfully exported:

Step 2: Import & Merge Multiple CSV Files

Next, we’ll use the following code to import and merge all three CSV files into one data frame in R:

library(dplyr)
library(readr)

#import and merge all three CSV files into one data frame
df <- list.files(path='C:/Users/bob/Documents/my_data_files') %>% 
  lapply(read_csv) %>% 
  bind_rows 

#view resulting data frame
df

# A tibble: 13 x 2
   points assists
       
 1      4       3
 2      5       2
 3      5       4
 4      6       4
 5      8       6
 6      9       3
 7      2       3
 8     10       2
 9     14       9
10     15       3
11      6      10
12      8       6
13      9       4

Notice that all three CSV files have been successfully merged into one data frame.

We can see that the resulting data frame has 13 rows and 2 columns.

Note: If the data frames do not have matching column names, R will still merge all of the data frames and simply fill in missing values with NA values.

Additional Resources

The following tutorials explain how to work with other file types in R:

How to Import Excel Files into R
How to Import TSV Files into R
How to Import Zip Files into R
How to Import SAS Files into R
How to Import .dta Files into R

Leave a Reply

Your email address will not be published.