Philipp
Philipp

Reputation: 371

if not conditions in R?

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)

Upvotes: 25

Views: 88977

Answers (3)

EdS
EdS

Reputation: 1

How about this?

fun <- function(x){
ifelse(x > 0, "not bigger than zero", "zero or less")
}
fun(5)
[1] "Bigger than zero"

Upvotes: 0

nullglob
nullglob

Reputation: 7023

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"

Upvotes: 45

Shane
Shane

Reputation: 100174

Try:

if(!condition) { do something }

Upvotes: 5

Related Questions