在 R 程序中要求用户输入的正确方法是什么?
如果我分别运行下面的程序(分为两部分),它们就可以工作——也就是说,如果我将第一部分粘贴到 R 控制台中,运行它,然后粘贴第二部分并运行它.然而,这不是我想要的.我想一次运行整个程序.如果我这样做,它会在我的控制台中显示以下错误:
The my program below(which is in two parts) works if I run them separately – that is, if I paste the first part into the R Console, run it and then paste the second and run it. However, that is not how I want it. I want to run the whole program at once. If I do that it shows the following error in my console :
1:
Read 0 items
1:
Read 0 items
Error in while ((n <= 0) | (acr <= 0) | (acr >= 1)) { :
argument is of length zero
我已尝试确定问题,但无法找到根本原因.如果有人可以帮助我,我会非常高兴.
I have tried to identify the problem but I have not been able find the root cause. I would be more than glad, if someone could come to my aid.
#**FIRST PART OF THE PROGRAM**
n <- -2
acr <- -2
while((n<=0) | (acr<=0) | (acr>=1)) {
print("enter a positive integer and the average cancellation rate between 0 and 1
you want")
try(n <- scan(what=integer(), nmax=1), silent=TRUE)
try(acr <- scan(what=double(), nmax=1), silent=TRUE)
}
#**SECOND PART OF THE PROGRAM**
bygrace <- read.table("C:\\MyRfolder\\bygrace.txt", header=FALSE)
r <- nrow(bygrace)
c <- ncol(bygrace)
copybygrace <- array(bygrace, dim=c(r, c))
copybygrace <- bygrace[-((n+1):r), ]
write.table(copybygrace,file="C:\\MyRfolder\\copybygrace.txt", sep="\t")
copybygrace <- read.table("C:\\MyRfolder\\copybygrace.txt", header=TRUE)
@Marek 说得很对.补充几点:
@Marek is very right. A few more remarks :
- 一般来说,你不应该使用
scan()
而应该使用readline()
. - 我会拆分代码,以便清楚哪些内容适合在 n 中读取,哪些内容适合在 acr 中读取.
- 想想您是想在人们按 Enter 键时返回提示,还是想重新提问直到他们填写正确的值.
- 您可以使用
grepl()
的强大功能来检查输入的格式是否正确.
- In general, you shouldn't be using
scan()
butreadline()
for this. - I'd split the code so it becomes clear what serves to read in n, and what serves to read in acr.
- think about whether you want to return to the prompt when people just press enter, or whether you want to reask the question until they fill in some correct value.
- you can use the power of
grepl()
to check whether the input is the right format.
为了包含正确的控件并捕获所有可能的错误,以下构造更加简洁,并且在复制到控制台时不会破坏您的代码:
To include the correct controls and catch all possible mistakes, the following construct is a lot cleaner and won't break your code when copied to the console :
while(n < 1 ){
n <- readline("enter a positive integer: ")
n <- ifelse(grepl("\\D",n),-1,as.integer(n))
if(is.na(n)){break} # breaks when hit enter
}
这显示了当人们不填写任何内容时如何终止问题.grepl 构造排除了任何不是数字的字符,包括点.
This shows how to terminate the question when people don't fill in anything. The grepl construct exludes any character that is not a digit, including the dot.
while(is.na(acr) | acr <= 0 | acr >= 1 ){
acr <- readline("and the average cancellation rate between 0 and 1 :")
acr <- ifelse(grepl("[^0-9.]",acr),-1,as.numeric(acr))
}
这显示了当人们没有填写任何内容时如何重新提问.grepl 排除任何不是数字或点的字符.
This shows how to re-ask the question when people don't fill in anything. The grepl excludes any character that is not a digit or a dot.