使用R将多个文件从多个文件夹复制到一个文件夹

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

你好我想问一下如何使用R语言将多个文件夹中的多个文件复制到一个文件夹中

假设有三个文件夹:

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

在每个sub_task文件夹中,有多个文件。我想复制 sub_task 文件夹中的所有文件并将它们粘贴到桌面上的一个新文件夹(让我们将这个新文件夹命名为 "all_sub_task")。谁能告诉我如何使用循环或应用函数在 R 中执行此操作?提前致谢。

这是一个 R 解决方案。

# 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)
}

编辑为以编程方式列出 sub_task 个目录。

此代码应该有效。此函数获取一个目录——例如 desktop/folder_A/task/sub_task/——并将其中的所有内容复制到第二个目录。当然你可以使用循环或者申请一次使用多个目录,因为第二个值是固定的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 = '/'))
}