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?
Use dir.create(tempfile())
to create a uniquely named directory inside the R temporary directory. Repeat as necessary.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With