Oamar Kanji
Oamar Kanji

Reputation: 2224

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.

Upvotes: 0

Views: 1419

Answers (2)

Lindsay Hayes
Lindsay Hayes

Reputation: 21

I would like to point out that ggsave() does do this. But I don't think it works for saving objects but rather ggplot plot objects. i.e ggsave("plots/1.QC/plot1.jpg", width = 5, height = 5) will create a plots directory and a 1.QC subdirectory and save the last plot called plot1.jpg to that directory. I think it's a great function and also wish some of the save / saveRDS functions did this too.

Upvotes: 1

caldwellst
caldwellst

Reputation: 5956

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

Upvotes: 5

Related Questions