Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create multiple tempdirs in a single R session?

Tags:

r

temp

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?

like image 628
Michal Avatar asked Oct 20 '19 21:10

Michal


2 Answers

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

like image 101
Hong Ooi Avatar answered Sep 23 '22 13:09

Hong Ooi


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.

like image 44
prosoitos Avatar answered Sep 22 '22 13:09

prosoitos