In programming, we would like to control the execution of code. We can impose constraints on the execution of a statement based on a condition. These statements that allow us this power are called control statements. There are two types of control statements in R, if
and switch
If the condition is met perform task A
, else
perform task B
.
# pseudo code
if (condition_1 is True)
{
execute this line(s) of code
}else{
execute this line(s) of code
}
Now an example:
x <- seq(1:10)
if(length(x)<5){
# Task A
x^x
}else{
# Task B
x*10
}
## [1] 10 20 30 40 50 60 70 80 90 100
We can test for multiple conditions using:
(&&)
(||)
To elaborate:
if
, condition x
and (&&)
condition y
are satisfied, then perform task A
. Both conditions must be met for the execution of the statement.if
, condition x
or (||)
condition y
are satisfied, then perform task A
. If one of the conditions is met, execute the statement.x <- seq(10,100,10)
x
## [1] 10 20 30 40 50 60 70 80 90 100
if(length(x)<5 && sum(x)<100){
# Task A
x^x
}else if(length(x)<5 || sum(x)>100){
# Task B
x^10
}else if(length(x)<5 && sum(x)==100){
# Task C
x-x
}
## [1] 1.000000e+10 1.024000e+13 5.904900e+14 1.048576e+16 9.765625e+16
## [6] 6.046618e+17 2.824752e+18 1.073742e+19 3.486784e+19 1.000000e+20
A switch
function can be used to avoid writing multiple lines of if
. Given an expression, it returns a specific value that matches the expression.
# pseudo code
switch(expression, conditon_1="You get this",condition_2="You get something else")
Now an example:
x <- "A"
switch(x,"A"=10,"B"=20,"C"=30,"D"=40)
## [1] 10
x <-"D"
switch(x,"A"=10,"B"=20,"C"=30,"D"=40)
## [1] 40
Introduction to R by Dr. Sarath Chandra Dantu
This course material is available under a Creative Commons BY-SA license (CC BY-SA) version 4.0