2013-08-25 174 views
1

我試圖用R打開RStudio中使用的.Rproj文件。我已成功使用下面的代碼(從Ananda here盜取)。但是,打開文件後,從R調用的打開RStudio的連接並未關閉。 打開.Rproj文件後,如何切斷此「連接」?(PS尚未在Linux或Mac上測試過)。系統打開RStudio關閉連接

## 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) 
+2

Downvoter保健佳品,爲什麼這樣我就可以改善這個問題? –

+0

你嘗試過'closeAllConnections()'嗎? –

+0

@Roman通常情況下,這可能會起作用,但是這個用法是用在一個包中的,我記得Yihui說過使用'closeAllConnections'是不好的,因爲你不知道其他包中的其他連接可能會關閉。 –

回答

4

目前還不清楚你想要做什麼。你所描述的對我來說聽起來並不像一個「連接」 - 這是一個system電話。

認爲什麼你在說的是,你在上面的例子中運行open_project(loc)後,你沒有得到你的[R提示回來,直到你關閉一個由你的函數打開RStudio的實例。如果是這種情況,您應該將wait = FALSE添加到您的system通話中。

您可能還需要在其中添加一個ignore.stderr = TRUE以直接回到提示。我在我的Ubuntu系統上遇到了一些關於「QSslSocket:無法解析SSLv2_server_method」的錯誤,在我點擊「回車」後,我又回到了提示符。 ignore.stderr可以繞過(但也可能意味着用戶在嚴重錯誤的情況下不會得到有意義的錯誤)。

換句話說,我會改變你的open_project()功能,下面看看它做你所期望的:

open_project <- function(Rproj.loc) { 
    action <- paste(wheresRstudio(), Rproj.loc) 
    message("Preparing to open project!") 
    system(action, wait = FALSE, ignore.stderr = TRUE) 
} 
+0

正是我之後的事情。再次感謝。 –

+2

請注意,所有'wait = FALSE'都會將'&'添加到命令的末尾。 – hadley

+0

@hadley感謝您的補充信息。 –