Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change tempdir() in session (update R_TempDir)

Tags:

c

r

cran

I am looking for a way to change the tempdir() location after an R session has started. I think it would be required to update the C level global variable R_TempDir. What would be a nice way to do this from within R?

like image 658
Jeroen Ooms Avatar asked Apr 25 '12 19:04

Jeroen Ooms


3 Answers

Update: Simon Urbanecks unixtools package has a function to accomplish this. Below the code (for future reference).

set.tempdir <- function(path) {
  invisible(.Call(C_setTempDir, path.expand(path)))
}

C code:

#include <string.h>
#include <Rinternals.h>
#include <Rembedded.h>

SEXP C_setTempDir(SEXP sName) {
    if (TYPEOF(sName) != STRSXP || LENGTH(sName) != 1)
    Rf_error("invalid path");
    R_TempDir = strdup(CHAR(STRING_ELT(sName, 0)));
    return sName;
}
like image 68
Jeroen Ooms Avatar answered Nov 08 '22 08:11

Jeroen Ooms


If you unlock tempdir() and re-assign a new function to the baseenv() it might work:

tempdir <- function() "/NewTempDir"
unlockBinding("tempdir", baseenv())
assignInNamespace("tempdir", tempdir, ns="base", envir=baseenv())
assign("tempdir", tempdir, baseenv())
lockBinding("tempdir", baseenv())
like image 5
L.R. Avatar answered Nov 08 '22 08:11

L.R.


It's awfully cheesy, but you could just mask base::tempdir by saying

tempdir <- function() { "[desired temp dir here]" }

Then you'd be OK as long as you weren't using code that (implicitly or explicitly) looked in the base namespace before the global environment ...

I really don't see any other way to do this, since it's set at initialization time and not altered thereafter. In other words, Sys.setenv(TMPDIR="/home/bolker/R") doesn't work -- it's too late (as you probably know).

If tempdir() were less hard-coded it would be a lot easier ... I don't really understand the design criteria here (or, less charitably, whether there were carefully thought-out design criteria ...). (I feel similarly grumpy about the hard-coding/design of .libPaths(), which is similar ... no way to change things once you're in a running R session.)

like image 4
Ben Bolker Avatar answered Nov 08 '22 07:11

Ben Bolker