在r中合并具有相同名称的文件,并将其写入R中的不同文件 [英] Combining files with same name in r and writing them into different files in R
问题描述
我有两个文件夹,两个文件的名称相同。例如-FOLDER1具有a.csv,b.csv,c.csv,类似地FOLDER2具有a.csv,b.csv和c.csv
I have two folders with files having same names. e.g - FOLDER1 has a.csv, b.csv, c.csv and similarly FOLDER2 has a.csv, b.csv , c.csv
文件的编号不同行,但列数和列名相同
the files have different number of rows but the same number and name of columns
我要合并名称相同的文件,并将其写入名称为a.csv,b.csv c的文件中.csv。
I want to combine files with the same name and write them into files with the name a.csv, b.csv c.csv.
这只是一个示例,我想对800-1000个文件使用。
This is just an example and I want to do it for 800-1000 files.
我试过
filenames <- list.files(c(filePathNew,filePath), pattern="*.csv", full.names=TRUE)
具有两个文件夹中的所有文件名
has all the filenames from the two folders
lst1 <- lapply(split(filenames, basename(filenames)),function(x) do.call(rbind,
lapply(x,function(y) read.csv(y, header = TRUE, stringsAsFactors = FALSE, sep = ""))))
lapply(seq_along(lst1), function(i) write.csv(lst1[[i]], paste(filepath,names(lst1)[i], sep = "/"), row.names = FALSE,
quote = FALSE))
,但显示以下错误
Error in rbind(deparse.level, ...) :
numbers of columns of arguments do not match
Called from: stop("numbers of columns of arguments do not match")
推荐答案
再次更新
正如您现在已经指出的那样,您可以使用Windows,可以使用保存为 CONCAT.BAT
As you have now indicated you have Windows, you could use something like this saved as CONCAT.BAT
CD FOLDER1
MKDIR COMBINED
FOR %%G IN (*.CSV) DO COPY "%%G"+FOLDER2\"%%G" COMBINED\"%%G"
然后做
system("CONCAT.BAT", intern=FALSE)
更新后的答案
由于文件数量多于最初建议的3个,因此可以使用名为 concat
像这样:
As you have more files than the 3 you initially suggested, you could use a script called concat
like this:
#!/bin/bash
cd FOLDER1
for f in *.csv; do cat "$f" FOLDER2/"$f" > "combined${f}"; done
使其可执行并使用
system("chmod +x concat; ./concat", intern=FALSE)
原始答案
如果在Unix / Linux上,请尝试:
If on Unix/Linux, try:
system("cat FOLDER1/a.csv FOLDER2/a.csv > aCombined.csv", intern=FALSE)
如果在Windows上,请尝试:
If on Windows, try:
system("copy FOLDER1\a.csv+FOLDER2\a.csv aCombined.csv", intern=FALSE)
这篇关于在r中合并具有相同名称的文件,并将其写入R中的不同文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!