Search code examples
rautomationworking-directorysetwd

Automatically Set Working Directory to Currently Opened Folder in R


Is it possible in R to set the working directory to a currently opened folder automatically?

Example: Let's assume that I have currently opened the folder example_dir on my computer.

enter image description here

Now, I want to run some R code to set this folder as my working directory without knowing the name of the opened folder. The R code should look like this:

currently_opened_folder <- xxxxxxx some function extracting the path for example_dir xxxxxxxx
setwd(currently_opened_folder)

Solution

  • I just found out how to get location URL from Explorer windows thanks to this article.

    First, execute a command in PowerShell to retrieve the path of the active Explorer windows. Then, use grep to extract the paths from the command return. Finally, you need to remove the "file:///" prefix and decode the URL (replacing special characters like "%20").

    # Get location URL of opened Explorer windows
    location_url <- grep(
      "file", 
      system('powershell -command "$a = New-Object -com "Shell.Application"; $b = $a.windows() | select-object LocationURL; $b"', intern = TRUE),
      value = TRUE
    )
    
    # Check if there are multiple windows opened
    if (length(location_url) > 1) {
      message("Multiple Explorer windows are opened.")
    } else {
      # Clean paths
      path <- gsub("file:///", "", URLdecode(location_url))
      setwd(path)
    }