Search code examples
rfiledirectorysubdirectory

Switch r settings to not have to create directory when saving files into new subfolders


I have code to create new files saving graphics into new subfolders like the following:

library(tidyverse)
library(ggplot2)

carb_list = unique(mtcars$carb)

  
iterate = function(z){
  
df  = mtcars |> filter(carb == z)

df |> 
  ggplot(aes(x=cyl,y=mpg)) + geom_point()

ggsave(filename = paste0("new/carb",z,"/plot.png"))
  
}

sapply(carb_list, iterate)

However, each time this runs, it causes me to have to approve the creation of a new subfolder, as I receive this prompt in the console:

Cannot find directory new/carb4.
ℹ Would you like to create a new directory?

This used to never be the case, as it would automatically create a new subfolder for me, and not require manual approval. But on the most recent r update [4.3.3 (Angel Food Cake)] it now requires this every time.

Is there a way to configure r so that it never asks, and just automatically creates the subfolders? I say configure because I would like this to always apply on every file/project. I have seen other workarounds where you can tell it to create a folder with a function if not already created, but it appears on an individual basis for each file name/folder. I do not want this, I would instead like the old way where it automatically generates the subfolder, as I have too many different subfolders/files to do this one-by-one.


Solution

  • This is not actually caused by a change in your R version but was introduced in ggplot2 3.5.0:

    ggsave() no longer sometimes creates new directories, which is now controlled by the new create.dir argument (#5489).

    You can set this to TRUE to recursively create directories:

    iterate <- function(z) {
        df <- mtcars |> filter(carb == z)
    
        df |>
            ggplot(aes(x = cyl, y = mpg)) +
            geom_point()
    
        ggsave(filename = paste0("new/carb", z, "/plot.png"), create.dir = TRUE)
    }
    

    General approach

    More generally, e.g. with other plotting libraries, you can use dir.create(recursive = TRUE) to create directories if they do not exist.

    iterate <- function(z) {
        df <- mtcars |> filter(carb == z)
    
        df |>
            ggplot(aes(x = cyl, y = mpg)) +
            geom_point()
    
        outfile  <- paste0("new/carb",z,"/plot.png")
        outdir  <- dirname(outfile)
        if(!dir.exists(outdir)) dir.create(outdir, recursive = TRUE)
        ggsave(filename = outfile)
    }