Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy multiple files from multiple folders to a single folder using R

Hey I want to ask how to copy multiple files from multiple folders to a single folders using R language

Assuming there are three folders:

  1. desktop/folder_A/task/sub_task/
  2. desktop/folder_B/task/sub_task/
  3. desktop/folder_C/task/sub_task/

In each of the sub_task folder, there are multiple files. I want to copy all the files in the sub_task folders and paste them in a new folder (let's name this new folder as "all_sub_task") on desktop. Can anyone show me how to do it in R using the loop or apply function? Thanks in advance.

like image 401
kelvinfrog Avatar asked Feb 09 '23 06:02

kelvinfrog


2 Answers

Here is an R solution.

# Manually enter the directories for the sub tasks
my_dirs <- c("desktop/folder_A/task/sub_task/", 
             "desktop/folder_B/task/sub_task/",
             "desktop/folder_C/task/sub_task/")

# Alternatively, if you want to programmatically find each of the sub_task dirs
my_dirs <- list.files("desktop", pattern = "sub_task", recursive = TRUE, include.dirs = TRUE)

# Grab all files from the directories using list.files in sapply
files <- sapply(my_dirs, list.files, full.names = TRUE)

# Your output directory to copy files to
new_dir <- "all_sub_task"
# Make sure the directory exists
dir.create(new_dir, recursive = TRUE)

# Copy the files
for(file in files) {
  # See ?file.copy for more options
  file.copy(file, new_dir)
}

Edited to programmatically list sub_task directories.

like image 182
ialm Avatar answered Feb 16 '23 04:02

ialm


This code should work. This function takes one directory -for example desktop/folder_A/task/sub_task/- and copies everything there to a second one. Of course you can use a loop or apply to use more than one directory at once, as the second value is fixed sapply(froms, copyEverything, to)

copyEverything <- function(from, to){
  # We search all the files and directories
  files <- list.files(from, r = T)
  dirs  <- list.dirs(from, r = T, f = F)    


  # We create the required directories
  dir.create(to)
  sapply(paste(to, dirs, sep = '/'), dir.create)

  # And then we copy the files
  file.copy(paste(from, files, sep = '/'), paste(to, files, sep = '/'))
}
like image 26
durum Avatar answered Feb 16 '23 04:02

durum