【问题标题】:Binding csv files and outputing result in same subfolder and looping绑定csv文件并在相同的子文件夹中输出结果并循环
【发布时间】:2017-10-01 07:12:16
【问题描述】:

在尝试了几个小时的不同代码后,我正在寻求帮助。我有一个文件夹,有五个子文件夹。每个子文件夹包含三个 csv 文件。我想在每个子文件夹中 cbind 这三个 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=",")
}

【问题讨论】:

    标签: r file loops subdirectory


    【解决方案1】:

    这就是我处理它的方式。下面是一个完整的示例,它将在您选择的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)
    })
    

    【讨论】:

    • 代码运行良好,非常感谢 Roman Lustrik。我对其进行了一些修改以读取 csv 文件并使用 cbind 水平绑定它们。当使用 cbind 而不是 rbind 时,我需要自己解决两个问题:(1)列名以文件路径名为前缀; (2) 从子文件夹中的每个文件中仅导入某些列 [,14:17]。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 2020-05-08
    • 2011-04-15
    • 1970-01-01
    • 2017-10-06
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多