Make R wait for console input?

不羁岁月 提交于 2019-12-04 10:18:13

readline can only be used in interactive sessions. In non-interactive use of readline the result is an empty string. On the help page of ?interactive you find the following about interactive sessions:

GUI consoles will arrange to start R in an interactive session. When R is run in a terminal (via Rterm.exe on Windows), it assumes that it is interactive if ‘stdin’ is connected to a (pseudo-)terminal and not if ‘stdin’ is redirected to a file or pipe. Command-line options --interactive (Unix) and --ess (Windows, Rterm.exe) override the default assumption.

Try scan function.

This is test.R file:

y <- 2
cat('y=',y)
cat("\nEnter username")
x <- scan(what=character(),nmax=1,quiet=TRUE)
"ala ma kota"
y <- 2*2
cat('y=',y)
cat('\nx=',x)

and then I run this:

> source("test.R")
y= 2
Enter username
1: login
y= 4
x= login

--edit-- To read only one character quietly run this:

> x <- scan(what=character(),nmax=1,quiet=TRUE)
1: username
> x
[1] "username"

what sets the type, nmax sets the maximal numbers of elements to read and quiet determine if print a line, saying how many items have been read.

Why not putting

source("script2.R")

into the file script1.R?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!