绑定 csv 文件并在同一子文件夹中输出结果并循环

Binding csv files and outputing result in same subfolder and looping

我在尝试不同的代码几个小时后寻求帮助。我有一个文件夹,有五个子文件夹。每个子文件夹都有三个 csv 文件。我想在每个子文件夹中绑定这三个 csv 文件,并将结果输出到同一个子文件夹中,对每个子文件夹执行相同的操作。因此,除了最初的 15 个 csv 文件外,我还将在这五个子文件夹中组合五个文件。我感谢您的帮助。我将以下代码行放在一起,但没有成功

#Folder containing sub-folders
parent.folder <- "path"

# Sub-folders
sub.folders <- list.dirs(parent.folder, recursive=TRUE)[-1]

# List files in all subfolders
files <- sapply(sub.folders, list.files, all.files = F, full.names = T, recursive=TRUE)


# Make a list of lists
mydata <- lapply(files, function(x) read.csv(x, header = T)[,14:17]) #list of lists, each has 4 variables


for (r in 1:length(mydata)){
fileatt <- paste("path","new_file",r,".csv",sep="")
write.table(mydata[r],fileatt, row.name=F, col.name=c("a","b","c","d"), quote=F,sep=",")
}

这就是我处理它的方式。下面是一个完整的示例,它将在您选择的 topdir 中创建三个子文件夹。它将用两个两列三行的文本文件填充每个子文件夹。

下一步是找到这些子文件夹,导入文件,按子文件夹合并它们并写入顶级目录。

## data generation

# top folder
topdir <- "test"
dir.create(topdir)

# create subfolders
subdirs <- c("sub1", "sub2", "sub3")
sapply(subdirs, FUN = function(x, topdir) dir.create(file.path(topdir, x)), topdir = topdir)

finddirs <- list.dirs(topdir, recursive = FALSE)

sapply(finddirs, FUN = function(x) {
  replicate(3, {
    fn <- sample(letters, 5, replace = TRUE)
    fn <- paste(paste(fn, collapse = ""), ".txt", sep = "")

    xy <- data.frame(a = 1:3, b = runif(3))

    write.table(xy, file = file.path(x, fn), row.names = FALSE, sep = "\t")
  })
})

## merging of files

# find subfolders
find.dirs <- list.dirs(topdir, recursive = FALSE)

# find files in dirs
files.in.dirs <- sapply(find.dirs, FUN = function(x) list.files(x, full.names = TRUE), simplify = FALSE)

# read files and merge into one data.frame
merged.by.subdir <- sapply(files.in.dirs, FUN = function(x) {
  xy <- sapply(x, read.table, sep = "\t", simplify = FALSE, header = TRUE)
  as.data.frame(do.call(rbind, xy))
}, simplify = FALSE)

# create main filenames per subfolder
bn <- basename(names(merged.by.subdir))
bn <- paste(bn, ".txt", sep = "")
bn <- file.path(topdir, bn)

# write data into folder
mapply(as.list(bn), merged.by.subdir, FUN = function(x, y) {
  write.table(y, file = x, row.names = FALSE)
})