'Open File Explorer at specified folder using R (or specifically R Studio) in Windows

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.



Solution 1:[1]

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/")

Solution 2:[2]

Use

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

which will open a file picker.

Solution 3:[3]

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)
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MS Berends
Solution 2 dash2
Solution 3 M. Rodo