You are on page 1of 3

if (test_expression) {

statement
}

Examples:

1)

x <- 5
if(x > 0){
print("Positive number")
}

2)

if(1==0) {
print(1)
} else {
print(2)
}

3)

Second type of ifelse condition:

Syntax: ifelse(test, truevalue, falsevalue)


ifelse operates on vectors therefore avoiding loops

Example:

1)

y=log(c(3,0.5,2,4))
ifelse(y<0,NA,y)

2)

x<-20:30
ifelse(x<26,x,x^2)
if (test_expression) {
statement1
} else {
statement2
}

Examples:

x <- -5
if(x > 0){
print("Non-negative number")
} else {
print("Negative number")
}

x=1:10
y=ifelse(x>5,1,-1)
z=ifelse(x>5,1,ifelse(x<2,-1,0))

Nested if...else statement:

if ( test_expression1) {
statement1
} else if ( test_expression2) {
statement2
} else if ( test_expression3) {
statement3
} else
statement4

Examples:
x <- 0
if (x < 0) {
print("Negative number")
} else if (x > 0) {
print("Positive number")
} else
print("Zero")

Examples:

Calculating median of a single sample


x=c(2,7,1,8,9)
med=function(x) { odd=length(x)%% 2
if (odd==0) {
med=(sort(x)[length(x)/2]+sort(x)[1+length(x)/2])/2
}
else med=sort(x)[ceiling(length(x)/2)]
}
m=med(x)

You might also like