if Statement in R:
The if-else combination is probably the most commonly used control structure not only in R but also for other programming languages. This structure allows you to test a condition and act on it depending on whether it’s true or false.
if statement in R:
The syntax of if statement is:
if (condition) {
#R Code
}
x<-200
if(x > 100){
print("X is greater than 100")
}
Output:
[1] "X is greater than 100"
If the condition is TRUE, the statement gets executed. But if it’s FALSE, nothing happens. Here, condition can be a logical or numeric vector, but only the first element is taken into consideration.
You could have a series of if clauses that always get executed if their respective conditions are true.
if(condition1) {
R Code
}
if(condition2) {
R Code
}
if…else statement in R:
In R, the if/else syntax is:
if (condition) {
R code
} else {
R code
}
if-else:
x <- readline(prompt="Enter a number: ") #Take input from user. Then run the next line.
y <- if(x > 10){
print("Value is greater than 10")
} else {
print("Value is less than or equal to 10")
}
Output:
> x <- readline(prompt="Enter a number: ")
Enter a number: 11
[1] "Value is more than 10"
Example:
x = 4
y = 6
if (x > y) {
print("x is larger than y")
} else {
print("x is less than or equal to y")
}
Output:
[1] "x is less than or equal to y"
ifelse() Function in R:
This is called Vectorization with ifelse. The ifelse() function is a vector equivalent form of the if…else statement in R. This vectorization of code, will be much faster than applying the same function to each element of the vector individually.
So, you can use if-else like this also
ifelse(4 > 3, "greater","less")
Output:
[1] "greater"
This is how we use ifelse() to a vector.
x<- 1:20
ifelse(x> 10, "greater", "less")
Output:
[1] "less" "less" "less" "less" "less" "less" "less" "less" "less" "less" "greater" "greater"
[13] "greater" "greater" "greater" "greater" "greater" "greater" "greater" "greater"
Nested if…else statement in R:
x <- 0
if (x < 0) {
print("Negative number")
} else if (x > 0) {
print("Positive number")
} else
print("Zero")
Output:
[1] "Zero"
For loops are most commonly used for iterating over the elements of an object (list, vector, etc.)
for Loops in R:
Here is a for loop example in R.
for(i in 1:10) {
print(i)
}
x <- c("a", "b", "c", "d")
for(i in 1:4) {
print(x[i])
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
>
> x <- c("a", "b", "c", "d")
> for(i in 1:4) {
+ print(x[i])
+ }
[1] "a"
[1] "b"
[1] "c"
[1] "d"
Print out each element of ‘x’.
for(letter in x) {
print(letter)
}
Output:
[1] "a"
[1] "b"
[1] "c"
[1] "d"
For one line loops, the curly braces are not strictly necessary.
for(i in 1:4) print(x[i])
Output:
[1] "a"
[1] "b"
[1] "c"
[1] "d"
Nested for loops in R:
for loops can be nested inside of each other like the below example.
x <- matrix(1:10, 5, 2)
for(i in seq_len(nrow(x))) {
for(j in seq_len(ncol(x))) {
print(x[i, j])
}
}
Output:
[1] 1
[1] 6
[1] 2
[1] 7
[1] 3
[1] 8
[1] 4
[1] 9
[1] 5
[1] 10
While loops begin by testing a condition. If it is true, then they execute the loop body. Once the loop body is executed, the condition is tested again, and so forth, until the condition is false, after which the loop exits.
Syntax of while loop:
while (condition)
{
R Code
}
Example:
count <- 0
while(count < 10) {
print(count)
count <- count + 1
}
Output:
[1] 0
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
Another Example:
z <- 8
set.seed(1) #set.seed() is used for reproducible results.
while(z >= 6 && z <= 10){
coin <- rbinom(1, 1, 0.5)
if(coin == 1) {
print("It is head")
z <- z + 1
} else {
print("It is tail")
z <- z - 1
}
}
Output:
[1] "It is tail"
[1] "It is tail"
[1] "It is head"
[1] "It is head"
[1] "It is tail"
[1] "It is head"
[1] "It is head"
[1] "It is head"
[1] "It is head"
repeat loop in R:
A repeat loop is used to iterate over a block of code multiple number of times. There is no condition check in repeat loop to exit the loop. The only way to exit a repeat loop is to call break. These are not commonly used in statistical or data analysis applications but they do have their uses.
Syntax of repeat loop:
repeat {
R Code
if(…){
R Code
break
}
}
Example:
x <- 5
repeat {
print(x)
x = x+1
if (x == 10){
break
}
}
Output:
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
Another Example:
set.seed(1)
repeat {
x<-runif(1, 5, 10)
print(x)
if(x < 6){
break
}
}
Output:
[1] 6.327543
[1] 6.860619
[1] 7.864267
[1] 9.541039
[1] 6.00841
[1] 9.491948
[1] 9.723376
[1] 8.303989
[1] 8.14557
[1] 5.308931
next and break in R:
Example of next:
for(i in 1:10) {
if(i <= 5) {
# Skip the first 5 iterations
next
}
print(i)
}
Output:
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
Example of break:
for(i in 1:100) {
print(i)
if(i > 3) {
print(i)
# Stop loop after 3 iterations
break
}
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 4
R has some very useful functions which implement looping in a compact form to make the life easier. The very rich and powerful family of apply functions is made of intrinsically vectorized functions. These function in R allow you to apply some function to a series of objects (eg. vectors, matrices, dataframes or files). They include:
lapply(): Loop over a list and evaluate a function on each element
sapply(): Same as lapply but try to simplify the result
apply(): Apply a function over the margins of an array
tapply(): Apply a function over subsets of a vector
mapply(): Multivariate version of lapply
There is another function called split() which is also useful, particularly in conjunction with lapply.
Control structures in R allow you to control the flow of execution of a series of R expressions.
Commonly used control structures are
if and else: testing a condition and acting on it
for: execute a loop a fixed number of times
while: execute a loop while a condition is true
In R, the if/else syntax is:
if (…) {
R code
} else {
R code
}
#Take input from user. Then run the next line.
x <- readline(prompt="Enter a number: ")
y <- if(x > 10){
print("Value is greater than 10")
} else {
print("Value is less than or equal to 10")
}
Output:
> x <- readline(prompt="Enter a number: ")
Enter a number: 11
[1] "Value is more than 10"
x = 4
y = 6
if (x > y) {
print("x is larger than y")
} else {
print("x is less than or equal to y")
}
Output:
[1] “x is less than or equal to y”
You can use if-else like this also
ifelse(4 > 3, "greater","less")
Output:
[1] "greater"
This is how we use ifelse() to a vector.
x<- 1:20
ifelse(x> 10, "greater", "less")
Output:
[1] "less" "less" "less" "less" "less" "less" "less" "less" "less" "less" "greater" "greater"
[13] "greater" "greater" "greater" "greater" "greater" "greater" "greater" "greater"
Here is a for loop example in R.
for(i in 1:10) {
print(i)
}
x <- c("a", "b", "c", "d")
for(i in 1:4) {
print(x[i])
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
>
> x <- c("a", "b", "c", "d")
> for(i in 1:4) {
+ print(x[i])
+ }
[1] "a"
[1] "b"
[1] "c"
[1] "d"
Print out each element of ‘x’.
for(letter in x) {
print(letter)
}
Output:
[1] "a"
[1] "b"
[1] "c"
[1] "d"
For one line loops, the curly braces are not strictly necessary.
for(i in 1:4) print(x[i])
Output:
[1] "a"
[1] "b"
[1] "c"
[1] "d"
for loops can be nested inside of each other like the below example.
x <- matrix(1:10, 5, 2)
for(i in seq_len(nrow(x))) {
for(j in seq_len(ncol(x))) {
print(x[i, j])
}
}
Output:
[1] 1
[1] 6
[1] 2
[1] 7
[1] 3
[1] 8
[1] 4
[1] 9
[1] 5
[1] 10
count <- 0
while(count < 10) {
print(count)
count <- count + 1
}
Output:
[1] 0
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9