Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in R Programming by (50.2k points)

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?

1 Answer

0 votes
by (108k points)

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"

It can be checked with as.logical

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.

Browse Categories

...