tags:

views:

130

answers:

3

Hi there,

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)

Best wishes Philipp

+3  A: 

Try:

if(!condition) { do something }
Shane
I already tried that, but it's not the solution :-(added a simple example above.
Philipp
Your example works.
Shane
you are right... shame on me ^^
Philipp
A: 

How about this?

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

fun(5)

[1] "Bigger than zero"
EdS
ifelse should only be used for vectors of length > 1
Eduardo Leoni
+3  A: 

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"
nullglob
thanks, it's working fine now :-)
Philipp