Read system TMP dir in R
Asked Answered
C

1

7

What is a cross-platform method to find the OS temporary directory from within R? I currently use:

dirname(tempdir())

Which did the job both on Ubuntu and Windows from within an interactive R session. However, then it failed when called from inside RApache. In RApache the value of tempdir() is always /tmp, so dirname(tempdir()) results in /, which is obviously wrong. I also tried:

Sys.getenv("TMP")
Sys.getenv("TEMP")
Sys.getenv("TMPDIR")

as suggested by ?"environment variables" but none of these were set in Ubuntu. It also doesn't seem to be set in any of the files in /etc/R/* so I don't quite understand how R detects this value.

Cantaloupe answered 10/5, 2013 at 3:25 Comment(2)
Why tempdir() always return /tmp is puzzling. Do you have write access to that dir?Josefina
I think rApache sets the C level global R_TempDir to implement some caching. See github.com/jeffreyhorner/rapacheCantaloupe
T
4

The environment variables "TMPDIR", "TMP", and "TEMP" can be used to modify the value returned by tempdir() if the C variable R_TempDir isn't set (although I'm not sure how that is done). If you want a cross-platform function that will return the path of a reasonable tmp directory, and aren't interested in the value of R_TempDir, you could use something like this:

gettmpdir <- function() {
  tm <- Sys.getenv(c('TMPDIR', 'TMP', 'TEMP'))
  d <- which(file.info(tm)$isdir & file.access(tm, 2) == 0)
  if (length(d) > 0)
    tm[[d[1]]]
  else if (.Platform$OS.type == 'windows')
    Sys.getenv('R_USER')
  else
    '/tmp'
}

This is based on the function InitTempDir in the file src/main/sysutils.c from the R source distribution, translated from C to R.

Trihedron answered 10/5, 2013 at 23:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.