Skip to content

Instantly share code, notes, and snippets.

@brfitzpatrick
Created April 22, 2016 21:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brfitzpatrick/2fed259975e51d761d3963e42f45c9c1 to your computer and use it in GitHub Desktop.
Save brfitzpatrick/2fed259975e51d761d3963e42f45c9c1 to your computer and use it in GitHub Desktop.
Read all files in a directory into R
# general demo
setwd('~/Documents/directory_of_csv_files/')
# create a collection of .csv files names following some system
X <- expand.grid(LETTERS,1:10)
for(i in 1:nrow(X)){
Data.i <- data.frame(matrix(data = rnorm(1000), nrow = 10))
colnames(Data.i) <- paste(X[i,1], X[i,2], 'C',1:ncol(Data.i), sep='.')
name.i <- paste(paste('Boring_Bit_of_File_Name', X[i,1], X[i,2], sep = '_'), 'csv', sep = '.')
write.csv(file = paste(name.i), x = Data.i)
}
rm(list = ls()) # clear the workspace
ls()
# read the list of file names in the specified directory into a character vector
file.names <- list.files(path = '~/Documents/directory_of_csv_files/')
# read in each file in the directory naming it with the interesting bit of the filename
for(i in 1:length(file.names)){
start.stripped.i <- unlist(strsplit(x = file.names[i], split = 'Boring_Bit_of_File_Name_'))[2]
obj.name.i <- unlist(strsplit(x = start.stripped.i, split = '\\.'))[1] # escape character before . so it's not treated as a wildcard
X.i <- read.csv(file.names[i])
assign(x = obj.name.i, value = X.i)
rm(list = c('start.stripped.i', 'obj.name.i', 'X.i'))
gc()
}
ls()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment