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?
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;
}
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())
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.)
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