I am trying to write an interactive R script. For example:
我正在尝试编写一个交互式R脚本。例如:
try.R:
try.R:
print("Entr some numbers. >",quote=F)
a = scan(what=double(0))
print a
q()
Now, if I run it on the command line as
现在,如果我在命令行上运行它
$ R --no-save < try.R
It tries to get the stdin from try.R, giving the following error:
它试图从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
I tried a few other methods but they all give errors. For example:
我尝试了其他一些方法,但都会出错。例如:
$ R CMD BATCH try.R
$ Rscript try.R
So how do I write an R script that works from the *nix shell command line, and can take in interactive input from the user?
那么如何编写一个可以从* nix shell命令行运行的R脚本,并且可以从用户那里获取交互式输入?
3 个解决方案
#1
19
Try this:
尝试这个:
cat("What's your name? ")
x <- readLines(file("stdin"),1)
print(x)
Hopefully some variant of that works for you.
希望有些变体适合你。
#2
4
What worked for me on Windows with RStudio 0.98.945 and R version 3.1.1 was:
在Windows上使用RStudio 0.98.945和R版本3.1.1对我有用的是:
cat("What's your name? ")
x <- readLines(con=stdin(),1)
print(x)
#3
0
The answer by @Joshua Ulrich is fine for Linux, but hangs under macOS and needs to be terminated using Ctrl-D.
@Joshua Ulrich的答案适用于Linux,但在macOS下挂起并需要使用Ctrl-D终止。
This is a work-around for both Linux and macOS:
这是Linux和macOS的解决方法:
#!/usr/bin/env Rscript
print(system("read -p 'Prompt: ' input; echo $input", intern = TRUE))
#1
19
Try this:
尝试这个:
cat("What's your name? ")
x <- readLines(file("stdin"),1)
print(x)
Hopefully some variant of that works for you.
希望有些变体适合你。
#2
4
What worked for me on Windows with RStudio 0.98.945 and R version 3.1.1 was:
在Windows上使用RStudio 0.98.945和R版本3.1.1对我有用的是:
cat("What's your name? ")
x <- readLines(con=stdin(),1)
print(x)
#3
0
The answer by @Joshua Ulrich is fine for Linux, but hangs under macOS and needs to be terminated using Ctrl-D.
@Joshua Ulrich的答案适用于Linux,但在macOS下挂起并需要使用Ctrl-D终止。
This is a work-around for both Linux and macOS:
这是Linux和macOS的解决方法:
#!/usr/bin/env Rscript
print(system("read -p 'Prompt: ' input; echo $input", intern = TRUE))