### Control Structures

Control structures in R allow you to control the flow of execution of a series of R expressions.

Commonly used control structures are

1.  if and else: testing a condition and acting on it
2.  for: execute a loop a fixed number of times
3. while: execute a loop while a condition is true

In R, the if/else syntax is:

if (…) {

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”

`x = 4y = 6if (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:20ifelse(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"`

#### for loop:

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])
}
}

[1] 1
[1] 6
[1] 2
[1] 7
[1] 3
[1] 8
[1] 4
[1] 9
[1] 5
[1] 10

#### while Loops:

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