如果输入无效,重新提示 readline()
Re-prompt readline() if the input is invalid
假设我想要求用户输入一个大于 10 的数字。如果没有,打印一条消息并再次 re-prompt/ask。这在 R 中如何实现?
我知道这可以通过 IF 或 WHILE 语句解决,但我无法解决这个问题。
例子
math <- function(number_1) {
number_1 <- readline("Enter your number: ")
if the number is below i want to reprompt readline(...)
result <- number_1 / 2
return(result)
}
这里有一个方法:
math <- function() {
result <- NA
while (is.na(result) || result < 10) {
text <- readline("Enter your number: ")
result <- as.numeric(text)
}
result
}
您不需要为您的函数提供任何输入;它会在提示用户时获得输入。 is.na(result)
代码检查 NA
:最初的结果是 NA
,因此它将 运行 循环至少一次,如果
用户输入的不是数字,你会得到另一个。
由于 readline()
returns 是字符值,您需要 as.numeric
将其转换为数字。
假设我想要求用户输入一个大于 10 的数字。如果没有,打印一条消息并再次 re-prompt/ask。这在 R 中如何实现? 我知道这可以通过 IF 或 WHILE 语句解决,但我无法解决这个问题。
例子
math <- function(number_1) {
number_1 <- readline("Enter your number: ")
if the number is below i want to reprompt readline(...)
result <- number_1 / 2
return(result)
}
这里有一个方法:
math <- function() {
result <- NA
while (is.na(result) || result < 10) {
text <- readline("Enter your number: ")
result <- as.numeric(text)
}
result
}
您不需要为您的函数提供任何输入;它会在提示用户时获得输入。 is.na(result)
代码检查 NA
:最初的结果是 NA
,因此它将 运行 循环至少一次,如果
用户输入的不是数字,你会得到另一个。
由于 readline()
returns 是字符值,您需要 as.numeric
将其转换为数字。