Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read system TMP dir in R

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.

like image 925
Jeroen Ooms Avatar asked May 10 '13 03:05

Jeroen Ooms


1 Answers

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.

like image 191
Steve Weston Avatar answered Sep 22 '22 02:09

Steve Weston