I installed two external training data files with a package that I want the user to choose from using file.choose(). I can find them using system.file('extdata',package='myPackage'), but I want the user to easily open them through the chooser without having to run system.file().
Since users may not know where the packages are saved or how to navigate from there, how do I give them the ease of use they're accustomed to in Windows and MacOS?
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"