如何在脚本中包含要从命令行运行的交互式输入

时间:2010-10-14 16:15:26

标签: r

我正在尝试编写一个交互式R脚本。例如:

try.R:

print("Entr some numbers. >",quote=F)
a = scan(what=double(0))
print a
q()

现在,如果我在命令行上运行

$ R --no-save < try.R

它尝试从try.R获取stdin,给出以下错误:

> print("Entr some numbers. >",quote=F)
[1] Entr some numbers. >
> a = scan(what=double(0))
1: print a
Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  : 
  scan() expected 'a real', got 'print'
Execution halted

我尝试了其他一些方法,但都会出错。例如:

$ R CMD BATCH try.R 
$ Rscript try.R 

那么如何编写一个可以从* nix shell命令行运行的R脚本,并且可以从用户那里获取交互式输入?

3 个答案:

答案 0 :(得分:21)

试试这个:

cat("What's your name? ")
x <- readLines(file("stdin"),1)
print(x)

希望有些变体适合你。

答案 1 :(得分:4)

在Windows上使用RStudio 0.98.945和R版本3.1.1对我有用的是:

    cat("What's your name? ")
    x <- readLines(con=stdin(),1)
    print(x)

答案 2 :(得分:0)

@Joshua Ulrich的答案适用于Linux,但在macOS下挂起,需要使用Ctrl-D终止。

这是Linux和macOS的解决方法:

#!/usr/bin/env Rscript

print(system("read -p 'Prompt: ' input; echo $input", intern = TRUE))