How to create multiple tempdirs in a single R session?
Asked Answered
I

2

10

I need to create multiple temp directories during a single R session but every time I call tempdir() I get the same directory.

Is there an easy way to ensure that every call will give me a new temp directory?

Insobriety answered 20/10, 2019 at 21:45 Comment(2)
Would creating subdirectories of your tempdir work? If so, you can do dir.create(paste0(tempdir(), "/1")), dir.create(paste0(tempdir(), "/2")), etc.Claudicant
tempdir returns the pre-session temp directory - I think there can be only one. Maybe create temp subdirectory in tempdir() and then use tempfile to access them?Airspeed
F
10

Use dir.create(tempfile()) to create a uniquely named directory inside the R temporary directory. Repeat as necessary.

Fogdog answered 20/10, 2019 at 23:28 Comment(0)
C
4

You can only have one tempdir. But you could create subdirectories in it and use those instead.

If you want to automate the creation of those subdirectories (instead of having to name them manually), you could use:

if(dir.exists(paste0(tempdir(), "/1"))) {
  dir.create(paste0(
    tempdir(), paste0(
      "/", as.character(as.numeric(sub(paste0(
        tempdir(), "/"
      ),
      "", tail(list.dirs(tempdir()), 1))) + 1))))
} else {
  dir.create(paste0(tempdir(), "/1"))
}

This expression will name the first subdirectory 1 and any subsequent one with increment of 1 (so 2, 3, etc.).

This way you do not have to keep track of how many subdirectories you have already created and you can use this expression in a function, etc.

Claudicant answered 20/10, 2019 at 22:6 Comment(4)
Thank you for your answer. Looks like this is the way to go. However with this explicit solution I’d need to track the global state of the final dir index to be able to always create a new one. Do you think there’s a way to make it more generic? So that a call to some function with this logic always works?Insobriety
I updated my answer to make it work automatically, without having to keep track of the index nor having to manually name the subdirectoriesClaudicant
This is much more complicated than necessary. See my answerFogdog
Indeed... Dang :DClaudicant

© 2022 - 2024 — McMap. All rights reserved.