3

I'm attempting to use R to open a .Rproj file used in RStudio. I have succeeded with the code below (stolen from Ananda here). However, the connection to open RStudio called from R is not closed after the file is opened. How can I sever this "connection" after the .Rproj file is opened? (PS this has not been tested on Linux or Mac yet).

## Create dummy .Rproj
x <- c("Version: 1.0", "", "RestoreWorkspace: Default", "SaveWorkspace: Default", 
    "AlwaysSaveHistory: Default", "", "EnableCodeIndexing: Yes", 
    "UseSpacesForTab: No", "NumSpacesForTab: 4", "Encoding: UTF-8", 
    "", "RnwWeave: knitr", "LaTeX: pdfLaTeX")

loc <- file.path(getwd(), "Bar.rproj")
cat(paste(x, collapse = "\n"), file = loc)

## wheresRStudio function to find RStudio location 
wheresRstudio <- 
function() {
    myPaths <- c("rstudio",  "~/.cabal/bin/rstudio", 
        "~/Library/Haskell/bin/rstudio", "C:\\PROGRA~1\\RStudio\\bin\\rstudio.exe",
        "C:\\RStudio\\bin\\rstudio.exe")
    panloc <- Sys.which(myPaths)
    temp <- panloc[panloc != ""]
    if (identical(names(temp), character(0))) {
        ans <- readline("RStudio not installed in one of the typical locations.\n 
            Do you know where RStudio is installed? (y/n) ")
        if (ans == "y") {
                temp <- readline("Enter the (unquoted) path to RStudio: ")
        } else {
            if (ans == "n") {
                stop("RStudio not installed or not found.")
            }
        }
    } 
    temp
}

## function to open .Rproj files
open_project <- function(Rproj.loc) {
    action <- paste(wheresRstudio(), Rproj.loc)
    message("Preparing to open project!")
    system(action)
}


## Test it (it works but does no close)
open_project(loc)
Community
  • 1
  • 1
Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519

1 Answers1

5

It's not clear what you're trying to do exactly. What you've described doesn't really sound to me like a "connection" -- it's a system call.

I think what you're getting at is that after you run open_project(loc) in your above example, you don't get your R prompt back until you close the instance of RStudio that was opened by your function. If that is the case, you should add wait = FALSE to your system call.

You might also need to add an ignore.stderr = TRUE in there to get directly back to the prompt. I got some error about "QSslSocket: cannot resolve SSLv2_server_method" on my Ubuntu system, and after I hit "enter" it took me back to the prompt. ignore.stderr can bypass that (but might also mean that the user doesn't get meaningful errors in the case of serious errors).

In other words, I would change your open_project() function to the following and see if it does what you expect:

open_project <- function(Rproj.loc) {
    action <- paste(wheresRstudio(), Rproj.loc)
    message("Preparing to open project!")
    system(action, wait = FALSE, ignore.stderr = TRUE)
}
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485