首页 > 解决方案 > 使用循环在R中移动多个文件

问题描述

我知道有一些问题与我的非常相似,但我有不同而奇怪的问题。

我正在编写一个脚本,它将文件从一个位置存档到另一个位置。问题是,当我在循环中对多个文件使用 file.rename() 时,或者如果我尝试在 1 行中使用旧路径向量和新路径向量时,R 不会移动文件。例如

for (i in 1:length(old_files_all)) {
  try(file.rename(from = file.path(old_files_all[i]), to = file.path(new_paths[i])))
  #or without try/file.path inside of method ^
}

这样的循环不会移动文件,但是当我为循环的每个位置手动运行代码时,例如:

try(file.rename(from = file.path(old_files_all[1]), to = file.path(new_paths[1])))

有用....

你们能帮我吗,如何解决这个“问题”。提前致谢。

标签: r

解决方案


您可以直接将 file.rename 与向量一起使用,无需循环。

#create some example files
file.create(paste0("test", formatC(1:10, width = 2, flag = "0"), ".txt"))
#create vectors with old and new file names
files_old <- list.files(pattern = "^test[0-9]{2}\\.txt", getwd())
files_new <- paste0(getwd(), "//Delete//", files_old)

#move files
file.rename(from = files_old, to = files_new)

推荐阅读