readinteger <- function() { n <- readline(prompt="Enter an integer: ") return(as.integer(n)) } print(readinteger())
Enter an integer: 88 [1] 88
The readline function
readline() lets the user enter a one-line string at the terminal.
The prompt argument is printed in front of the user input. It usually ends on ": ".
The as.integer function
as.integer makes an integer out of the string.
Preventing failure if no number is entered
Right now if the user doesn't enter an integer, as.integer will return NA (Not Available). We can avoid this by using is.na to check the user input and asking again if the value is NA:
readinteger <- function() { n <- readline(prompt="Enter an integer: ") n <- as.integer(n) if (is.na(n)){ n <- readinteger() } return(n) } print(readinteger())
Enter an integer: Enter an integer: boo Enter an integer: 44 [1] 44 Warning message: In readinteger() : NAs introduced by coercion
However, a warning message is still shown. This is how to avoid it:
readinteger <- function() { n <- readline(prompt="Enter an integer: ") if(!grepl("^[0-9]+$",n)) { return(readinteger()) } return(as.integer(n)) } print(readinteger())
Enter an integer: Enter an integer: 31r132weq Enter an integer: effasdf Enter an integer: 222 [1] 222
grepl returns TRUE if the regular expression "^[0-9]+$" is matched. (The expression checks for a string that consists of nothing but one or more digits.)
! negates the result and the if branch is executed if the user-entered string isn't an integer.