R if statement

If is used test the condition, if condition is true, R will run all of the code that appears between the braces{} that follow the if statement (i.e., between the { and } symbols). If this evaluates to FALSE, R will skip the code between the braces without running it and executes the code out of if condition.

R if Syntax:

if(condition) { do somtething } do rest of things

R if statement

Examples:

a<-1 #Declare variables a and b b<-2

1. Checks the variable a value equals to 1

if(a==1) { print("Welcome to k2schools") }

Output:
[1] “Welcome to k2schools”

2. Compares variables a and b are equal or not.

if(a==b) { print("Welcome to k2schools") } print("a and b are not equal")


Output:

[1] “a and b are not equal”

3. Following condition test variables are numeric or not.

if(is.numeric(a) && is.numeric(b)) { print(a+b) }

Output:
[1] 3

4. Following if condition test both variables are null or not.

if(!is.null(a) && !is.null(b)) { print(a+b) }

Output:
[1] 3

Powered by WordPress