简体   繁体   English

R:在 For 循环中使用 dir.create 时出现问题

[英]R: Problem using dir.create within a For loop

I'm building a file directory consisting of a set of folders for years 2023-2030, each containing twelve subfolders (one for every calendar month).我正在构建一个文件目录,其中包含一组 2023-2030 年的文件夹,每个文件夹包含十二个子文件夹(每个日历月一个)。 The following code correctly prints the file paths I'm trying to create:以下代码正确打印了我尝试创建的文件路径:

library(lubridate)

path <- "C:/Users/joeshmoe1/Documents/"

for(i in paste0(format(seq(Sys.Date() %m+% years(1), length.out=8, by="+1 years"), "%Y"),"-YTD")) {
  if (!file.exists(paste0(path, i))) {dir.create(path = paste0(path, i))} 
  else {print(paste0(path, i, "/", paste0(format(ISOdate(year(Sys.Date() %m+% years(1)), 1:12, 1), "%m"), "-", month.abb)))}
}

 [1] "C:/Users/joeshmoe1/Documents/2023-YTD/01-Jan"
 [2] "C:/Users/joeshmoe1/Documents/2023-YTD/02-Feb"
 [3] "C:/Users/joeshmoe1/Documents/2023-YTD/03-Mar"
...
[10] "C:/Users/joeshmoe1/Documents/2030-YTD/10-Oct"
[11] "C:/Users/joeshmoe1/Documents/2030-YTD/11-Nov"
[12] "C:/Users/joeshmoe1/Documents/2030-YTD/12-Dec"

However, in the else section, when I swap the print function above for a dir.create function, an error message appears:但是,在else部分,当我将上面的print函数替换为dir.create函数时,会出现一条错误消息:

for(i in paste0(format(seq(Sys.Date() %m+% years(1), length.out=8, by="+1 years"), "%Y"),"-YTD")) {
  if (!file.exists(paste0(path, i))) {dir.create(path = paste0(path, i))} 
  else {dir.create(path = paste0(path, i, "/", paste0(format(ISOdate(year(Sys.Date() %m+% years(1)), 1:12, 1), "%m"), "-", month.abb)), showWarnings = FALSE)}
}

Error in dir.create(paste0(paste0(path, i), "/", paste0(format(ISOdate(year(Sys.Date() %m+%  : 
  invalid 'path' argument

Why is the error message occurring, and what might I change to fix it?为什么会出现错误消息,我可以更改哪些内容来修复它?

You only need to nest another for loop to create each folder's set:您只需要嵌套另一个 for 循环来创建每个文件夹的集合:

library(lubridate)

path <- "C:/Users/joeshmoe1/Documents/"

for(i in paste0(format(seq(Sys.Date() %m+% years(1), length.out=8, by="+1 years"), "%Y"),"-YTD")) {
 if (!file.exists(paste0(path, i))) {dir.create(path = paste0(path, i))} 
 else {
  for (j in paste0(format(ISOdate(year(Sys.Date() %m+% years(1)), 1:12, 1), "%m"), "-", month.abb)) {
    dir.create(path = paste0(path, i, "/", j))
  }
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM