我有一个脚本,我想用键盘输入启动它然后根据此变量中输入的值继续工作,我尝试了y=readline("please enter a value")
但脚本不会等待输入值,它只显示这句话并继续,如何做到这一点???
提前谢谢??
答案 0 :(得分:6)
这是一个非常简单的#!
脚本,它创建一个函数foo()
,其唯一目的是回显它的参数'bar'
。
#! /home/gavin/R/2.13-patched/build/bin/Rscript --vanilla
foo <- function(bar) {
writeLines(paste("You supplied the following information:", bar))
}
## grab command arguments passed as -args
args <- commandArgs(TRUE)
## run foo
foo(args)
我们使用commandArgs()
函数从shell获取传递给脚本的任何命令行参数,然后使用脚本的最后一行将它们传递给foo()
。
如果我们在文件foobar.R
中有一些代码,那么我们可以传入一个参数并使用Rscript
接口运行脚本。您还需要制作上述可执行文件(chmod
)。
然后可以调用脚本,并按如下方式工作:
[gavin@desktop ~]$ ./foobar.R Cl
You supplied the following information: Cl
但请注意?Rscript
中的信息,遗憾的是,标准Windows cmd shell不知道#!
类似脚本,因此您可能需要安装其他一些shell(帮助建议使用Cygwin shell)应该工作)使用我展示的功能。
更新:使用source()
和readline()
。
另一种方法是,如果你不必非交互式运行(即你不要打开R GUI并运行一行代码),那就是source()
脚本。例如,如果这是在脚本调用中barfoo.R
:
dynamicwilcox <- function() {
ANSWER <- readline("What column do you want to work on? ")
if(ANSWER=="Ph") {
writeLines("column was 'Ph'")
} else if(ANSWER=="Cl") {
writeLines("column was 'Cl'")
} else {
writeLines(paste("Sorry, we don't know what to do with column", ANSWER))
}
ANSWER ## return something
}
dynamicwilcox()
然后从R Gui提示,我们可以做到:
R> source("barfoo.R")
What column do you want to work on? Cl
column was 'Cl'
或者如果您不想指定完整路径,请执行以下操作:
R> source(file.choose())
readline()
在交互式R会话中使用时效果很好,并且确实是最适合工作的工具 - 这正是它的设计目标。
您希望以批处理模式运行脚本但提供一些输入的整个前提没有多大意义。 R期望在批处理模式下运行时脚本是自包含的。您可能没有意识到这一点,但是当您双击脚本时,它将以批处理模式运行。
答案 1 :(得分:2)
您可能需要scan()
,例如:
print("please enter a value")
y <- scan(file = "", what = "", nmax = 1)
scan()
将等待用户输入,任何文本都将存储在y
中 - 在这种情况下为模式字符向量。
答案 2 :(得分:0)
我在Ubuntu(不是Windows)上遇到了同样的问题并找到了解决方案。
而不是Rscript
使用littler(/usr/bin/r
)并确保将交互式标记-i
传递给更小的。这种组合设法说服readline()
在脚本中按照需要工作:
#!/usr/bin/r -vi
eprintf <- function(...) cat(sprintf(...), sep='', file=stderr())
prompt.read <- function(prompt="\n[hit enter to continue]: ") {
eprintf("%s", prompt)
invisible(readline())
}
ans <- prompt.read('Please enter a value: ')
eprintf("You have entered: '%s'\n", ans)
# rest of script comes here...
当我将其作为脚本运行时,我得到:
$ ./rl.r
Please enter a value: 42
You have entered: '42'
$ ./rl.r
Please enter a value: Hello to you!
You have entered: 'Hello to you!'
安装littler(在Ubuntu上):
sudo apt-get install littler