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?
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.
© 2022 - 2024 — McMap. All rights reserved.
dir.create(paste0(tempdir(), "/1"))
,dir.create(paste0(tempdir(), "/2"))
, etc. – Claudicanttempdir
returns the pre-session temp directory - I think there can be only one. Maybe create temp subdirectory intempdir()
and then usetempfile
to access them? – Airspeed