Lets say I want to ask the user for an input, a number over 10. If not, print a message and re-prompt/ask again. How can this be achieved in R? I understand that this could be solved with IF or WHILE statement, but I can´t wrap my head around this.
Example
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)
}
CodePudding user response:
Here's a way:
math <- function() {
result <- NA
while (is.na(result) || result < 10) {
text <- readline("Enter your number: ")
result <- as.numeric(text)
}
result
}
You don't need to give any input to your function; it will get the input when it prompts the user. The is.na(result)
code checks for an NA
: initially the result is NA
, so it will run the loop at least once, and if
the user enters something that isn't a number, you'll get another one.
Since readline()
returns a character value, you need as.numeric
to convert it to a number.