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

后端 未结 2 1576
无人及你
无人及你 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 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)
    

提交回复
热议问题