0

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?

pdw
  • 338
  • 2
  • 8
  • You can use `.libPaths` to reconstruct where the user *might* have packages installed, but ... why not use `system.file` to know where (if) packages are found? – r2evans Mar 17 '20 at 01:12
  • The catch is when the user calls my function, it pops up the file.chooser in the working directory. This package is for people with no programming knowledge or savvy and just need to accomplish a common task. I don't want to override setwd() with system.file. Is there a way to tell file.choose to start in a specific directory? – pdw Mar 17 '20 at 13:00

1 Answers1

0

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

file choose dialog

# 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 messages 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"
r2evans
  • 141,215
  • 6
  • 77
  • 149