【发布时间】:2018-03-17 11:06:31
【问题描述】:
在 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,或单击“运行”图标)——即使该选择是整个 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 拉入。
【问题讨论】:
-
RStudio 版本 1.0.153(截至发帖时最新)