2017-10-05 49 views
0

在RStudio IDE中,是否有一種運行選擇代碼的方法,它可以同時提交選擇的所有行(如全部運行,但是用於選擇),從而保持交互式本質命令menu()以交互方式運行代碼的選擇

背景

我有一個函數定義其次是一些命令,類似於:

f1 <- function(x){ 
    if(x == 'questionable_value'){ 
    if(menu(title = 'Detected a questionable value', 
       choices = c('[Abort process]', 
          'Continue with questionable value (not recommended)') 
      ) %in% c(0L,1L)){ 
     stop('Process stopped by user.') 
     } else warning('Questionable value ignored by user.') 
    } 
    return(paste('Did something with',x)) 
} 
f1('foo') 
f1('questionable_value') 
f1('bar') 

運行腳本(例如,在Windows RStudio IDE,運行所有或按Ctrl-Alt鍵-R ),按預期工作...

運行所有控制檯輸出(作品)

> source('~/.active-rstudio-document', echo=TRUE) 

> f1 <- function(x){ 
+ if(x == 'questionable_value'){ 
+  if(menu(title = 'Detected a questionable value', 
+    choices = c('[Abort .... [TRUNCATED] 

> f1('foo') 
[1] "Did something with foo" 

> f1('questionable_value') 
Detected a questionable value 

1: [Abort process] 
2: Continue with questionable value (not recommended) 

如果用戶輸入2,則:

Selection: 2 
[1] "Did something with questionable_value" 

> f1('bar') 
[1] "Did something with bar" 
Warning message: 
In f1("questionable_value") : Questionable value ignored by user. 

這就是我想要的。

問題當我運行選擇(例如,按Ctrl-Enter鍵,或點擊Run圖標)發生時 - 即使該選擇是整個R檔。

運行選擇控制檯輸出(不工作)

> f1 <- function(x){ 
+ if(x == 'questionable_value'){ 
+  if(menu(title = 'Detected a questionable value', 
+    choices = c('[Abort process]', 
+       'Continue with questionable value (not recommended)') 
+    ) %in% c(0L,1L)){ 
+  stop('Process stopped by user.') 
+  } else warning('Questionable value ignored by user.') 
+ } 
+ return(paste('Did something with',x)) 
+ } 
> f1('foo') 
[1] "Did something with foo" 
> f1('questionable_value') 
Detected a questionable value 

1: [Abort process] 
2: Continue with questionable value (not recommended) 

Selection: f1('bar') 
Enter an item from the menu, or 0 to exit 
Selection: 

在運行選擇的情況下,menu()不是等待用戶輸入,但在腳本的下一行,而不是拉( "f1('bar')")作爲Selection

+0

RStudio版本1.0.153(最新發布時間) – C8H10N4O2

回答

1

RStudio與標準R前端完全相同:「運行選擇」複製選定的文本,並將其粘貼到控制檯中。

爲了得到你想要的,你需要複製選定的文本和來自剪貼板。不幸的是,這並不是那麼容易的,但這裏的一些代碼,以幫助:

readClipboard <- function() { 
    if (.Platform$OS.type == "windows") 
    lines <- readLines("clipboard") 
    else 
    lines <- system("pbpaste", intern=TRUE) 
    lines 
} 

此功能在Windows上運行,並且有pbpaste指揮等系統。它內置在MacOS上,並且有在這裏模擬Linux的說明:https://whereswalden.com/2009/10/23/pbcopy-and-pbpaste-for-linux/

然後給源選定的文本,你需要將它複製(Ctrl-C鍵),然後運行

source(textConnection(readClipboard())) 

由於RStudio有一個API和安裝的命令(見https://rstudio.github.io/rstudioaddins/),你或許可以把所有的這(或等價物)轉換爲在按鍵上自動運行的代碼。 這裏有一個未經測試的版本:

library(rstudioapi) 
selection <- primary_selection(getSourceEditorContext())$text 
source(textConnection(selection)) 
相關問題