Reputation: 61
I have several csv files at a common location. Each csv file has the same column names but different data. The names of these csv files are different. Can I write a code in R to read in the data from all the csv files and then put it in a single data frame? The names of the csv files keep differing so I wish to have a code such that I do not have to explicitly specify the names of the csv files. Thanks.
Upvotes: 0
Views: 84
Reputation: 171
setwd("common location")
f <- list.files()
d <- data.frame()
for(i in 1:length(f)){
file <- read.csv(f[i],stringsasFactors=F)
d <- rbind(d,file)
}
colnames(d) <- c("col1","col2")
write.csv(d,"combined.csv",row.names=F)
Upvotes: 1
Reputation: 2359
filelist <- list.files(pattern = "\\.csv") # reads only .csv files in a folder
allcsv.files <- list()
count <- 1
for (file in filelist) {
dat <- read.csv(file)
allcsv.files[[count]] <- dat
count <- count + 1
}
allfiles <- do.call(rbind.data.frame, allcsv.files)
Upvotes: 2
Reputation: 18420
Have a look at list.files
for listing all files at a location, read.csv
for loading one file into R, and rbind
to put them into a single data.frame.
The code could look like this (untested)
setwd(location)
fnames <- list.files()
csv <- lapply(fnames, read.csv)
result <- do.call(rbind, csv)
Upvotes: 2