AlejandroDGR
AlejandroDGR

Reputation: 188

Why doesn't using two <= in a conditional statement work?

I'm writing an easy conditional structure:

numero = as.integer(readline(prompt="Elige un número cualquiera: "))

if(numero < 0){
  paste0("El número", numero, "es negativo.")
} else {
  if(0 <= numero <= 100){
     paste0("El número", numero, "está entre 0 y 100.")
  } else {
     paste0("El número", numero, "es mayor que 100.")
  }
}

However, when running this code an error arises:

Error in parse(text = x, srcfile = src): <text>:8:18: unexpected '<='
7: } else {
8:   if(0 <= numero <=                 ^

Why is this happening?

Upvotes: 0

Views: 49

Answers (2)

Sotos
Sotos

Reputation: 51592

It's not math. You need to be explicit.

Try if(0 <= numero && numero <= 100)

In addition, I would recommend to use the vectorised ifelse()

Upvotes: 1

Abdur Rohman
Abdur Rohman

Reputation: 2944

Your condition within if() is not coded properly. In addition, to make a space between strings in a sentence in this case, paste is better than paste0.

Here is an alternative fix:

numero = as.integer(readline(prompt="Elige un número cualquiera: "))
if(numero < 0){
    paste("El número", numero, "es negativo.")
} else {
    if(numero >=0 & numero <= 100){
        paste("El número", numero, "está entre 0 y 100.")
    } else {
        paste("El número", numero, "es mayor que 100.")
    }
}

Upvotes: 1

Related Questions