Created
February 25, 2021 14:26
-
-
Save Aariq/d76af5dcf6ef798c245a9b5887eabf86 to your computer and use it in GitHub Desktop.
Read in data spread across multiple .csv files or multiple sheets of .xlsx files.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Read in multiple .csv files with the same structure (same column names, numbers of columns, types of data in each column) and join them into a single data frame: | |
library(readr) | |
library(purrr) | |
root <- "path/to/where/my/data/is/" | |
file_paths <- list.files(root, pattern = "*.csv", full.names = TRUE) | |
#set the names of the file_paths vector, here I'll just use the file names, but you can use whatever | |
names(file_paths) <- list.files(root, pattern = "*.csv") | |
#read them all and join them | |
df <- map_df(file_paths, read_csv, .id = "filename") | |
# Read in multiple sheets of a .xlsx file and join into a single dataframe, extracting the sheet names as a column. | |
library(readxl) | |
library(purrr) | |
library(dplyr) | |
my_wkbk <- "~/Documents/example.xlsx" #replace with path to your excel workbook. | |
shts <- excel_sheets(my_wkbk) #gets sheet names | |
df <- | |
map(shts, ~read_excel(my_wkbk, sheet = .x)) %>% | |
set_names(shts) %>% | |
bind_rows(.id = "sheet_name") | |
#or, if you don't care about extracting the sheet names and including them in your data frame... | |
df <- map_df(shts, ~read_excel(my_wkbk, sheet = .x)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment