I noticed that if I pass any number except 0 as an argument to an if statement, the code inside the if statement compiles. I am confused why this is happening! I understand that R internally recognizes 0 as FALSE and the statement inside the if condition is not evaluated, which makes sense, but why is it getting evaluated for other numbers?
if(5) {
5 * 5
}
Run Code Online (Sandbox Code Playgroud)
I had expected that I will get an error, but the code compiles and I get 25 as an answer.
From the ifhelp page, if expects:
A length-one logical vector ... Other types are coerced to logical if possible, ignoring any class
So basically it does
as.logical(5)
# [1] TRUE
Run Code Online (Sandbox Code Playgroud)
既然是5 != 0,那就是真的
as.logical(0)
# [1] FALSE
Run Code Online (Sandbox Code Playgroud)
在语言中很常见,任何非0的数字都被解释为“ true”