rif-statementrelational-operators

How to use if statement in R?


I am habituated to Python where the following code works without any exceptions. However, I am getting the below error in R when I try to run the command.

a <- readline(prompt="Give a num between 1-10: ")
b <- readline(prompt="Give another between 11-20: ")

if((1 <= a <= 10) & (11 <= b <= 20)) {
  a <- a
  b <- b
} else {
  a <- readline(prompt="Give a correct num between 1-10: ")
  b <- readline(prompt="Give a correct num between 11-20: ")
}

Error:

enter image description here


Solution

  • 1) Although, 1 <= a <= 10 seems logically correct it isn't a valid syntax in R. You need to use 1 >= a & a <= 10 separately.

    2) output of readline is a character, you might want to wrap as.numeric to get a number.

    3) No need to assign a and b again, it is already present if the contion is TRUE.

    So to summarise you can do :

    a <- as.numeric(readline(prompt="Give a num between 1-10: "))
    b <- as.numeric(readline(prompt="Give another between 11-20: "))
    
    if(a < 1 | a > 10) 
       a <- as.numeric(readline(prompt="Give a correct num between 1-10: "))
    if(b < 11 | b > 20))
       b <- as.numeric(readline(prompt="Give a correct num between 11-20: "))