In R, perform the operation temporarily using a parameter such as a working directory

I am pretty sure I read somewhere how to do this. Instead of saving the current option (for example, the working directory) to a variable, change wd, perform the operation, and then go back to what it was, doing it inside the function, is akin to "c" regarding attach / detach. Now I only need a solution for the working directory, but maybe a more general function that does such things? Or isn’t it?

So, to illustrate ... As it is now:

curdir <- getwd()
setwd("../some/place")
# some operation
setwd(curdir)

How this happens in my wildest dreams:

with.dir("../some/place", # some operation)

I know that I could write a function for this, I have the impression that there is something more accessible and generalized for other parameters.

thank

+4
2

R

.
op <- par(no.readonly = TRUE)

# par(blah = stuff)
# plot(stuff)

par(op)

, options() setwd().

, :

with_dir <- function(dir, expr) {
    old_wd <- getwd()
    setwd(dir)
    result <- evalq(expr)
    setwd(old_wd)
    result
}

, evalq - . NSE Lumley, Wickham Advanced R, , .

: Ben Bolker, , on.exit :

with_dir <- function(dir, expr) {
    old_wd <- getwd()
    on.exit(setwd(old_wd))
    setwd(dir)
    evalq(expr)
}

R:

on.exit , , , ( ). .

+5

, , : , , , . Python , " ". , , Python "enter" "exit", .

with.default
function (data, expr, ...) 
eval(substitute(expr), data, enclos = parent.frame())
<bytecode: 0x07d02ccc>
<environment: namespace:base>

R with , . , "enter" "exit". , , R, .Internal.

, , - with, , , R.

+2

All Articles