How to write an if statement that stops code when any variable in a vector is outside of the limits provided?

Viewed 60

How do I write an if statement that stops code when any variable in the vector is outside of the intended sequence?

y <- c(1,2,3,4,11)

if(y > 10 | y < 0) 
    stop("Score has to be between 0 and 10")

Would it be done through loops? If so, which loop?

1 Answers

We can use

library(dplyr)
if(!all(between(y, 0, 10)) )

Or with stopifnot

stopifnot(all(y %in% 1:9))
Related