你找这样的事情吗?
do.call(rbind, lapply(list.files(path=".", pattern="AM-25"), read.table, header=TRUE, sep=","))
这会将包含字符“AM-25”的csv文件中读取的矩阵混合在一起。 read.table
的参数可能会有所不同,具体取决于您的csv文件。
编辑
我希望这个工程,你不知道在你的目录文件名的所有可能的五个字母前缀的情况:
##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=""))
由于这样的作品,但有什么方法可以在“模式”部分的文件名中使用拳头5个字符?我有多个csv文件,我无法在“模式”部分提供任何特定的术语。 – 2013-03-20 18:16:50
你的意思是说,包含例如子字符串“AM-25”**的非文件名**在开始时不匹配? list.files(path =“。”,pattern =“^ AM-25”)将匹配文件“AM-25.myfiles.2000.csv”“AM-25.myfiles.2001.csv”和“AM-25 .myfiles.2002.csv“而不是文件”otherfile_AM-25.myfiles.2000.csv“。你是这个意思吗? – user1981275 2013-03-21 10:57:00
是的,我正在处理这种格式的几个CSV文件,所以我正在寻找方法来破解名称中具有共同特征的所有文件。就像你用“AM-25”建议的那样。但是这些文件太多,我无法手动提供“模式”参数。 – 2013-03-21 16:06:17