is there anything like "if not" conditions in R?
easy Example (not working):
fun <- function(x)
{
if (!x > 0) {print ("not bigger than zero")}
}
fun(5)
Multiple Conditions To join two or more conditions into a single if statement, use logical operators viz. && (and), || (or) and ! (not). && (and) expression is True, if all the conditions are true.
To run an if-then statement in R, we use the if() {} function. The function has two main elements, a logical test in the parentheses, and conditional code in curly braces. The code in the curly braces is conditional because it is only evaluated if the logical test contained in the parentheses is TRUE .
The NOT operator, represented by an exclamation mark ! , simply negates the logical value it is used on. That is, ! TRUE evaluates to FALSE , while ! FALSE evaluates to TRUE .
if-elif-else statements in R allow us to build programs that can make decisions based on certain conditions. The if-elif-else statement consists of three parts: if. elif.
The problem is in how you are defining the condition. It should be
if(!(x > 0)){
instead of
if(!x > 0){
This is because !x
converts the input (a numeric) to a logical - which will give TRUE
for all values except zero. So:
> fun <- function(x){
+ if (!(x > 0)) {print ("not bigger than zero")}
+ }
> fun(1)
> fun(0)
[1] "not bigger than zero"
> fun(-1)
[1] "not bigger than zero"
Try:
if(!condition) { do something }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With