0) {print ("not bigg...">

If not conditions in R?

is there something like "if not" in R?

easy Example (doesn't work):

fun <- function(x) { if (!x > 0) {print ("not bigger than zero")} } fun(5) 

Regards Philippe

+6
r if-statement
source share
3 answers

The problem is how you define the condition. It should be

  if(!(x > 0)){ 

instead

  if(!x > 0){ 

This is because !x converts an input (numeric) to a logical one - 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" 
+23
source share

Try:

 if(!condition) { do something } 
+3
source share

How about this?

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

fun(5)

 [1] "Bigger than zero" 
0
source share

All Articles