Home > other >  Only allow specific values as input for scan() function
Only allow specific values as input for scan() function

Time:06-17

I want that only certain numbers can be used as input for the scan() function. Otherwise the input should be repeated until it is valid.

For example, the numbers 1:4 as first input and the numbers 1:8 as second input.

How can I achieve this?

# Only allow 1:4 as first input and 1:8 as second input  
input <- scan(what = numeric(), n = 2, quiet = TRUE)

CodePudding user response:

You can put scan in a while loop that checks the input, and repeats until valid input is received. Do this once for each number type required.

It's probably best to wrap this in a function:

get_input <- function() {
  input <- c(0, 0)
  vals1 <- 1:4
  vals2 <- 1:8
  
  cat("Enter a number between 1 and 4:\n")
  while(!input[1] %in% vals1){
    input[1] <- scan(what = numeric(), n = 1, quiet = TRUE)
    if(!input[1] %in% vals1)
      cat("Only numbers 1 to 4 allowed - try again")
  }
  
  cat("Enter a number between 1 and 8:\n")
  while(!input[2] %in% vals2){
    input[2] <- scan(what = numeric(), n = 1, quiet = TRUE)
    if(!input[2] %in% vals2)
      cat("Only numbers 1 to 8 allowed - try again")
  }
  
  return(input)
}

The function would work like this:

input <- get_input()
Enter a number between 1 and 4:
1: 7
Only numbers 1 to 4 allowed - try again
1: 3
Enter a number between 1 and 8:
1: 9
Only numbers 1 to 8 allowed - try again
1: 2
> input
[1] 3 2
  •  Tags:  
  • r
  • Related