Home > Mobile >  R: Problem using dir.create within a For loop
R: Problem using dir.create within a For loop

Time:12-20

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?

CodePudding user response:

Yo only have to nest another loop to create every 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))
  }
 }
}
  • Related