问题
I have multiple CSV files with 4 common character in their names. I want to know how I can rbind the files with the same common character. For example, "AM-25" is common in name of 3 csv files and "BA-35" in the name of another 2.
The files are like this AM-25.myfiles.2000.csv, AM-25.myfiles.2001.csv ,AM-25.myfiles.2002.csv,BA-35.myfiles.2000.csv, BA-35.myfiles.2001.csv, I use this to read in all the files:
files <- list.files(path=".", pattern="xyz+.csv", all.files = FALSE,full.names=TRUE )
回答1:
Do you look for something like this?
do.call(rbind, lapply(list.files(path=".", pattern="AM-25"), read.table, header=TRUE, sep=","))
This would rbind together the matrices read from your csv files which contain the characters "AM-25".
The arguments for read.table
could be different, depending on your csv files.
EDIT
I hope this works for the case that you do not know all possible five-letter prefixes of filenames in your directory:
##Get all different first five letter strings for all cvs files in directory "."
file.prefixes <- unique(sapply(list.files(path=".", pattern="*.csv"), substr, 1,5))
##Group all matching file names according to file.prefixes into a list
file.list <- lapply(file.prefixes, function(x)list.files(pattern=paste("^",x,".*.csv",sep=""), path="."))
names(file.list) <- file.prefixes ##just for convenience
##parse all csv files in file.list, create a list of lists containing all tables for each prefix
tables <- lapply(file.list, function(filenames)lapply(filenames, function(file)read.table(file, header=TRUE)))
##for each prefix, rbind the tables. Result is a list of length being length(file.prefixes)
## each containing a matrix with the combined data parsed from the files that match the prefix
joined.tables <- lapply(tables, function(t)do.call(rbind, t))
##Save tables to files
for (prefix in names(joined.tables))write.table(joined.tables[[prefix]], paste(prefix, ".csv", sep=""))
来源:https://stackoverflow.com/questions/15527720/import-and-rbind-multiple-csv-files-with-common-name-in-r