7

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?

Ola Ström
  • 4,136
  • 5
  • 22
  • 41
Michal
  • 6,411
  • 6
  • 32
  • 45
  • 1
    Would creating subdirectories of your tempdir work? If so, you can do `dir.create(paste0(tempdir(), "/1"))`, `dir.create(paste0(tempdir(), "/2"))`, etc. – prosoitos Oct 20 '19 at 22:03
  • `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? – kangaroo_cliff Oct 20 '19 at 22:04

2 Answers2

8

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

Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
3

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.

prosoitos
  • 6,679
  • 5
  • 27
  • 41
  • 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? – Michal Oct 20 '19 at 22:10
  • I updated my answer to make it work automatically, without having to keep track of the index nor having to manually name the subdirectories – prosoitos Oct 20 '19 at 22:57
  • 1
    This is much more complicated than necessary. See my answer – Hong Ooi Oct 20 '19 at 23:49
  • Indeed... Dang :D – prosoitos Oct 21 '19 at 00:33