Back
What happens if an if() statement doesn’t contain a logical expression?
For example, the if-else block if(2){print("A")}else{print("B")}) outputs A, but 2 is not true so it should print B. Why this is happening?
This is happening because any value other than 0 would be coerced to TRUE while 0 will be FALSE in the if statement in R programming:
if(2){print("A")}else{print("B")}#[1] "A"if(1) print("A")#[1] "A"if(0) print("A") else print("B")#[1] "B"
if(2){print("A")}else{print("B")}
#[1] "A"
if(1) print("A")
if(0) print("A") else print("B")
#[1] "B"
It can be checked with as.logical
as.logical(c(0, 1, 2, -1, 5, 3))#[1] FALSE TRUE TRUE TRUE TRUE TRUE
as.logical(c(0, 1, 2, -1, 5, 3))
#[1] FALSE TRUE TRUE TRUE TRUE TRUE
Here the TRUE will be mapped to 1 and FALSE to 0 as it is binary and if can have only two cases either TRUE or FALSE.
31k questions
32.8k answers
501 comments
693 users