I don't think you can do this without setwd
, but you don't have to keep it.
my_file_chooser <- function(d = getwd()) {
curdir <- getwd()
message("Currently in ", curdir)
on.exit({
setwd(curdir)
message("Returning to ", curdir)
}, add = TRUE)
setwd(d)
message("Showing file dialog in ", getwd())
file.choose()
}
my_file_chooser(system.file(package = "dplyr"))
# Currently in C:/Users/r2/StackOverflow
# Showing file dialog in C:/Users/r2/R/win-library/3.5/dplyr

# Returning to C:/Users/r2/StackOverflow
# [1] "C:\\Users\\r2\\R\\win-library\\3.5\\dplyr\\doc\\compatibility.Rmd"
getwd()
# [1] "C:/Users/r2/StackOverflow"
(You should probably remove all message
s before deploying a function like this.)
This is effectively what withr::with_dir
does, though it allows executing arbitrary code. If you don't mind another package (which might be installed anyway):
getwd()
# [1] "C:/Users/r2/StackOverflow"
withr::with_dir(system.file(package = "dplyr"), file.choose())
# [1] "C:\\Users\\r2\\R\\win-library\\3.5\\dplyr\\doc\\dplyr.html"
getwd()
# [1] "C:/Users/r2/StackOverflow"