1

Is there a way to open a File Explorer pane using a command in R/R Studio on Windows, with perhaps a path specified as the argument? For example:

open_folder(getwd())

would open File Explorer at the working directory. It would be like the opposite of choose.dir, in that you go from a path to File Explorer rather than from File Explorer to the path. It would be a command-line version of clicking on Files >> More >> Show Folder in New Window in R Studio.

I don't really know how to write code to work directly with Windows, so I'm looking for something that is already implemented or can be implemented just inside R.

MS Berends
  • 4,489
  • 1
  • 40
  • 53
M. Rodo
  • 448
  • 4
  • 12
  • See `rstudioapi::selectFile` and `...selectDirectory`. These aren't quite what you want (file dialogs not file explorer) but maybe close. – dash2 May 03 '21 at 13:52
  • Seems related to this similar question: https://stackoverflow.com/questions/35082201/set-the-rstudio-files-pane-directory-from-the-r-console (difference is that one is trying to utilize the RStudio "Files" pane for the picker, rather than the OS one). – Dannid May 01 '23 at 17:17

3 Answers3

9

The utils::browseURL() function is part of base R, since the utils package is installed as part of R. The function opens a URL, which can be of a website or a local folder.

So to open the current working directory in a File Explorer window:

utils::browseURL(getwd())

# or any other folder
utils::browseURL("myfolder/myfolder2/")
MS Berends
  • 4,489
  • 1
  • 40
  • 53
2

As it turns out, it's very simple for R to run PowerShell commands (see here), and then for PowerShell open to File Explorer (and not simply a dialogue box) at a given directory (see here).

Here is a wrapper function around base::system to do this:

od <- function(path = getwd()){
  path <- normalizePath(path)
  text_command <- paste0("powershell explorer ", path)
  system(text_command)
  invisible(TRUE)
}
M. Rodo
  • 448
  • 4
  • 12
  • 1
    It is very unwise to depend on PowerShell, because (1) it requires you to have PowerShell installed, (2) it becomes platform-dependent as PowerShell is not available for Linux or macOS, and (3) it is PowerShell. We're into R here, no need for other software :p – MS Berends Jan 26 '22 at 15:11
0

Use

rstudioapi::selectFile(path = "path/to/directory")

which will open a file picker.

dash2
  • 2,024
  • 6
  • 15
  • 1
    The fn `open_folder <- function(...) invisible(rstudioapi::selectFile(...))` wraps around this to avoid printing the chosen file path (or NULL, if no file were selected). – M. Rodo May 05 '21 at 08:04
  • 1
    This does not open a folder in File Explorer (Windows) or Finder (macOS) like the question was. Instead, it open a file *picker* (not even a folder picker). – MS Berends Jan 26 '22 at 15:00