使R等待控制台输入? [英] Make R wait for console input?
问题描述
有没有办法让R在继续之前先等待控制台输入? 假设我在一个名为run.R的主脚本中提供了两个这样的脚本:
Is there a way to make R wait for console input before continuing? Let's say I source two scripts like this in a main script called run.R:
# some more R Code here
source("script1.R")
source("script2.R")
# some more R Code there
Script1包含一些readLine
语句,要求用户输入用户名.
不幸的是,如果我只运行整个run.R文件,R不会等待输入用户名.它在输入用户名之前启动script2.R,这会导致错误,因为第二个脚本需要用户名.
Script1 contains some readLine
statement that asks the user for a username.
Unfortunately if I just run the entire run.R file R doesn't wait for the username to be entered. It starts script2.R before the username is entered which leads to an error because the 2nd script needs the username.
我使用R Studio的.rs.askForPassword
有一个丑陋的解决方法,它实际上等待输入,但包含密码.密码很酷,但用户名却不那么酷.加上它是RStudio功能,而不是R.
I have an ugly workaround for this using R Studio's .rs.askForPassword
which actually waits for the the input, but covers the password. Which is cool for passwords, but not so much for usernames. Plus it's an RStudio feature, not R.
推荐答案
尝试使用scan
函数.
这是test.R
文件:
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)
然后运行此命令:
> 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
设置类型,nmax
设置要读取的最大元素数,并且quiet
确定是否打印一行,说明已读取多少项.
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.
这篇关于使R等待控制台输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!