r-以交互方式运行代码选择



在RStudio IDE中,是否有一种方法可以同时提交所有选择行的代码的Run Selection(如Run all,但对于选择),而不是顺序提交,从而保留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中,Run All或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: 

在Run Selection的情况下,menu()不等待用户输入,而是拉入脚本的下一行("f1('bar')")作为Selection

RStudio在这里做了与标准R前端相同的事情:"Run Selection"复制所选文本,并将其粘贴到控制台中。

要获得所需内容,您需要从剪贴板复制选定的文本和源。不幸的是,这并不容易,但这里有一些代码可以帮助:

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

最新更新