R how to create file and directories at the same time

Usually in other languages when I create a file within some directors that do not currently exist those directories are created. Is this not the case with R and is there a way to automatically create directories when writing if a file if they do not exist?

  saveRDS(my_list, file="a_directory/another_directory/my_file.RDS)

gives an error as the directories do not yet exist.


I would argue that isn't common behavior in many languages, and each language often has a set of functions to deal with file structure on a machine. There is no automatic way to do this in R (how would that work with all the different functions for writing to files?), but you can just check directory existence and create if it doesn't exist prior to saving.

# OS independent file pathing
dir <- file.path("a_directory", "another_directory") 
if (!dir.exists(dir)) dir.create(dir)

saveRDS(my_list, file = file.path(dir, "my_file.RDS"))