虽然 Rstudio 中仍未内置此行为,但有几种方法可以帮助您实现所需的工作流程。
1。互动提示
readline 和 menu 函数允许您通过在终端中添加提示并接受输入作为响应来使您的脚本具有交互性。因此,如果您主要关心的不是每次在 Rstudio 中运行时都修改脚本,那么您可以设置一系列这些命令来每次都输入您的参数,如下所示:
x <- readline("What is your quest? ")
y <- menu(title = "What is your favorite color?", choices = c("Blue", "Clear"))
print(paste("Your quest is", x))
if (y == 1) print("Aaaaaargh!")
2。检测交互模式
一个相关的问题是希望能够在 Rstudio 中工作时更改脚本的参数,但不会阻止脚本在命令行上使用。这是脚本中硬编码参数的问题。虽然替换或覆盖commandArgs 可以更轻松地在一个地方提供所有参数,当需要使用完成的代码时可以将其注释掉,但这仍然不能解决问题。相反,请考虑检测您是否处于交互模式并相应地处理参数:
if (interactive()) {
opts <- c('grail')
} else {
opts <- commandArgs(trailingOnly = TRUE)
}
print(paste("I seek the", opts[1]))
3。使用 optparse 的默认值
如果您使用 optparse,它会变得更加容易。只需将每次调用中的default 参数设置为make_option,这将在您以交互方式运行程序时使用。这也可以与上述任一工作流程结合使用。
library(optparse)
opt_list <- list(make_option(
c("--quest"),
dest = 'your_quest',
type = 'character',
default = "the grail"
))
opt_parser <- OptionParser(option_list = opt_list)
opt <- parse_args(opt_parser)
print(paste("You seek", opt$your_quest))