简体   繁体   中英

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). 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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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