4

嘿我想问如何使用R语言将多个文件夹中的多个文件复制到单个文件夹中

假设有三个文件夹:

  1. 桌面/文件夹_A/任务/子任务/
  2. 桌面/文件夹_B/任务/子任务/
  3. 桌面/文件夹_C/task/sub_task/

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

4

2 回答 2

6

这是一个 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目录。

于 2015-12-17T22:30:03.493 回答
2

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 = '/'))
}
于 2015-12-18T18:06:20.060 回答