Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if not conditions in R?

Tags:

r

if-statement

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)
like image 606
Philipp Avatar asked Jun 10 '10 10:06

Philipp


People also ask

How do you write two conditions in an if statement in R?

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.

How do you write an IF THEN statement in R?

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 .

What is not in operator in R?

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 .

Does R have Elif?

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.


2 Answers

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"
like image 180
nullglob Avatar answered Oct 13 '22 19:10

nullglob


Try:

if(!condition) { do something }
like image 27
Shane Avatar answered Oct 13 '22 18:10

Shane