如何合并多个 excel 个文件
How to merge multiple excel files
我有多个 Excel 文件,每个文件有两列。对于不同的文件,一个相同,另一个不同。
如何按公共列合并所有文件并将它们另存为新文件?
注:
我不想将它们一个接一个地组合(使用 rbind
)。相反,我想 merge
他们基于公共专栏。
对于 R:
我有以下格式的文件名。
percent- 15 knt 03_01__00_51.csv
percent- 20 knt 03_01__00_54.csv
percent- 25 knt 03_01__00_57.csv
由于文件名格式的原因,我无法编写脚本来单独读取每个文件。我不知道如何编写一个只迭代 15 ,20 .... 并以某种方式留下结束部分的循环。
你或许可以这样做:
# if those are the only files in the folder, you don't even need a pattern
filelist <- list.files(pattern = "^percent.*\.csv$") # read all file names according to pattern
files <- lapply(filelist, read.csv, header=TRUE) # read all files in filelist
files <- lapply(files, function(x) x[-1]) # remove first column of each file
DF = Reduce(function(...) merge(..., by = "CommonColumn", all=T), files) # merge all files
x <- sub("^(percent- )(\d+)(\s.*)$", "\2", filelist) # get the file name numbers
names(DF[-1]) <- paste(names(DF[-1]), x, sep = "-") # add file name numbers to column names in DF
write.csv(DF, "myfile.csv") # write data to new file
Reduce()
部分取自here。
我有多个 Excel 文件,每个文件有两列。对于不同的文件,一个相同,另一个不同。
如何按公共列合并所有文件并将它们另存为新文件?
注:
我不想将它们一个接一个地组合(使用 rbind
)。相反,我想 merge
他们基于公共专栏。
对于 R:
我有以下格式的文件名。
percent- 15 knt 03_01__00_51.csv
percent- 20 knt 03_01__00_54.csv
percent- 25 knt 03_01__00_57.csv
由于文件名格式的原因,我无法编写脚本来单独读取每个文件。我不知道如何编写一个只迭代 15 ,20 .... 并以某种方式留下结束部分的循环。
你或许可以这样做:
# if those are the only files in the folder, you don't even need a pattern
filelist <- list.files(pattern = "^percent.*\.csv$") # read all file names according to pattern
files <- lapply(filelist, read.csv, header=TRUE) # read all files in filelist
files <- lapply(files, function(x) x[-1]) # remove first column of each file
DF = Reduce(function(...) merge(..., by = "CommonColumn", all=T), files) # merge all files
x <- sub("^(percent- )(\d+)(\s.*)$", "\2", filelist) # get the file name numbers
names(DF[-1]) <- paste(names(DF[-1]), x, sep = "-") # add file name numbers to column names in DF
write.csv(DF, "myfile.csv") # write data to new file
Reduce()
部分取自here。