示例数据
我正在编写一个脚本,目的是将输入文件复制到多个位置。以下是实现这一目标的功能代码示例:
##### File 1 #####
output_paths_1 <- list(c(paste0(path_1, "file_1", ".xlsx"),
paste0(path_2, "file_1", ".xlsx"),
paste0(path_3, "file_1", " ", gsub("-", "", Sys.Date()), ".xlsx")))
lapply(output_paths_1, function (x) file.copy(paste0(input_path, "input_1.xlsx"), x, overwrite = T))
##### File 2 #####
output_paths_2 <- list(c(paste0(path_1, "file_2", ".xlsx"),
paste0(path_2, "file_2", ".xlsx"),
paste0(path_3, "file_2", " ", gsub("-", "", Sys.Date()), ".xlsx")))
lapply(output_paths_2, function (x) file.copy(paste0(input_path, "input_2.xlsx"), x, overwrite = T))
##### File 3 #####
output_paths_3 <- list(c(paste0(path_1, "file_3", ".xlsx"),
paste0(path_2, "file_3", ".xlsx"),
paste0(path_3, "file_3", " ", gsub("-", "", Sys.Date()), ".xlsx")))
lapply(output_paths_3, function (x) file.copy(paste0(input_path, "input_3.xlsx"), x, overwrite = T))Reprex
但我怀疑有更有效的方法。在最近的一次尝试中,我使用了嵌套的“for”循环,这是不起作用的。我创建包含每个输入和文件名的数据帧。然后(理论上),对于inputs中的每个i,我为files中的每个i编写一个output paths数据框架。我使用grepl一次只为一个文件过滤这个数据帧。见下面的代码:
files <- data.frame(data = c("file_1", "file_2", "file_3"))
inputs <- data.frame(data = c("input_1.xlsx", "input_2.xlsx", "input_3.xlsx"))
for (i in seq_along(inputs)) {
for (i in seq_along(files)) {
output_paths <- data.frame(data = c(paste0(path_1, files[[i]], ".xlsx"),
paste0(path_2, files[[i]], ".xlsx"),
paste0(path_3, files[[i]], " ", gsub("-", "", Sys.Date()), ".xlsx"))) %>%
filter(grepl(files[[i]], `data`))
lapply(output_paths, function (x) file.copy(paste0(input_path, inputs[[i]]), x, overwrite = T))
}
}我预期这会将第一个文件复制到三个位置,然后再将下一个文件复制到相同的位置,等等。相反,会出现以下警告,并且只有第一个文件被复制到所需的位置:
Warning message:
In grepl(files[[i]], data) :
argument 'pattern' has length > 1 and only the first element will be used在不包含grepl函数的情况下运行代码根本不会做任何事情--不会将任何文件复制到所需的位置。
问题:
发布于 2021-12-17 20:22:46
我不明白你想用你的"Reprex“方法实现什么。但是,如果您想通过编写更少的代码来完成您的第一步代码,那么您可以执行以下操作
files = c("file1", "file2", "file3") # file names
opaths = c("path1", "path2", "path3") # output paths
df = expand.grid(file = files, path = opaths, stringsAsFactors = F)
df$from = file.path(input_path, df$file)
df$to = file.path(df$path, df$file)
file.copy(from = df$from, to = df$to)如果要在path3的文件名中使用时间戳,则可以执行以下操作
df$to[df$path == "path3"] <- file.path(df$path[df$path == "path3"],
paste0(format(Sys.Date(), "%Y%m%d_"), df$file[df$path == "path3"])
)https://stackoverflow.com/questions/70398212
复制相似问题