if statement in r code example
Example 1: r if else
# Basic syntax if:
if (test_expression) {
code to run if test_expression is true
}
# Basic syntax if else:
if (test_expression) {
code to run if test_expression is true
}
else {
code to run if test_expression is false
}
# Basic syntax if else if:
if (test_expression_1) {
code to run if test_expression_1 is true
}
else if (test_expression_2) {
code to run if test_expression_2 is true
}
# Basic syntax if else if else:
if (test_expression_1) {
code to run if test_expression_1 is true
}
else if (test_expression_2) {
code to run if test_expression_1 is true
}
else {
code to run if both expressions are false
}
Example 2: ifelse in r
> a = c(5,7,2,9)
> b = ifelse(a %% 2 == 0,"even","odd")
# b: odd odd even odd
Example 3: if and else if in r
if ( test_expression1) {
statement1
} else if ( test_expression2) {
statement2
} else if ( test_expression3) {
statement3
} else {
statement4
}