Using R to create folders sequentially based on previously existing folders

Viewed 160

I am attempting to use R to create folders sequentially and dynamically based on a given date. Starting with date_1 if there is no folder with the current date available. So for example, if a new folder was created today the initial result would look like:

/2020-05-15_1

Then subsequent folders would look like: /2020-05-15_2 /2020-05-15_3

Etc. The idea is to dynamically generate them sequentially each time the script is run.

I have been using a combination of sapply, list.dirs, sapply, and dir.create but can't anything to work and am a bit stuck. Any help would be much appreciated. Thanks!

1 Answers

The following creates folders according to your specifications.

# create today's date in format YYYY-MM-DD
today <- as.character(Sys.Date())

# create name of the first directory for today
first_today <- paste(today, 1, sep = "_")

# directories that exist in current working directory
dirs <- dir()

# check if the first directory already exists
if(first_today %in% dirs) {
  # subset to today's directories
  dirs_today <- dirs[grepl(today, dirs)]

  # get the number of todays directories
  n <- length(dirs_today)

  # create the name for today's next directory
  new_dir <- paste(today, n + 1, sep = "_")
  dir.create(new_dir)
} else {
  dir.create(first_today)
}
Related