Copying specific files from multiple sub-directories into a single folder in R

后端 未结 2 1575
无人及你
无人及你 2021-01-23 07:48

Assuming I have 3 folders with a large number of files in each, I want to select only a few files from each sub-directory and paste only those files into a new folder. Let\'s ca

相关标签:
2条回答
  • 2021-01-23 07:59

    Your my_dirs already contains full file names, and creating the files variable is not necessary.

    parent.folder <- "Desktop"
    ext <- ".jpg"                 # Wanted file extension
    
    my_dirs <- list.files(path = parent.folder, 
        full.names = TRUE, recursive = TRUE, include.dirs = TRUE)
    
    dir.create("Desktop/temp", recursive = TRUE)
    
    n <- sapply(my_dirs[grep(ext, my_dirs)], 
        FUN=function(x) file.copy(from = x, to = "Desktop/temp/"))
    
    message(paste("Number of files in", parent.folder, "with", ext, ":", length(n), 
        "(successully copied:", round(sum(n)/length(n)*100, 0), "%).")) 
    
    # Number of files in Desktop with .jpg : 4 (successully copied: 100 %).
    

    The variable n will contain a named logical vector, which you can explore in case of any problems in copying the files.

    0 讨论(0)
  • 2021-01-23 08:19
    parent.folder <- "C:/Desktop/dir"
    files <- list.files(path = parent.folder, full.names = T, recursive = T, include.dirs = T)
    

    After this you need to select the relevant files:

    files <- files[grep("wang\\.tax\\.sum", files)]
    

    (Notice double-escapes before dots: \\. - dot has a special meaning for grep.)

    Or you could do this with pattern argument to list.files in one step:

    files <- list.files(path = parent.folder, full.names = T, recursive = T, include.dirs = T, pattern = "wang\\.tax\\.sum")
    

    Creating new dir:

    dir.create("taxsum", recursive = T)
    

    Now you need to create new filenames:

    newnames <- paste0("taxsum/", gsub("/|:", "_", files))
    # replace "special" characters with underscore
    # so that your file names will be different and contain the 
    # original path
    
    # alternatively, if you know that file names will be different:
    newnames <- paste0("taxsum/", basename(files))
    

    And now you can use mapply to copy (the same can be done with for with a little extra effort):

    mapply(file.copy, from=files, to=newnames)
    
    0 讨论(0)
提交回复
热议问题