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

mwyxok5s  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(116)

我正在创建一个文件目录,其中包含一组2023-2030年的文件夹,每个文件夹包含12个子文件夹(每个日历月一个)。

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"

但是,在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

为什么会出现错误消息,我应该做哪些更改来修复它?

bq3bfh9z

bq3bfh9z1#

你只需要嵌套另一个循环来创建每个文件夹的集合:

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

相关问题