last updated: 2022-03-16

Control structures

Control structures allow you to set up conditions in a programming language, to ‘automate the boring stuff’


Outline

  • for() loop in R

  • while() conditions in R

  • if(), else() and ifelse()

  • for() example IRL

  • problems

for() loop in R

for() loops are used to repeat commands a certain number of times.

for(i in 1:10){
  
  <do this 10 times>

}

NB i is set to 1 and is incremented each cycle

NB2 i can be called anything (e.g. bob would work fine)

for() loop in R

What will this print?

for(bob in 1:25){
  print(paste("The number is", bob ))
}

while() conditions in R

while() sets a condition and a command executes while the condition is true

x = 1
  
# Print 1 to 5
while(x <= 5){
  print(x)
  x = x + 1  # condition increment
}

if(), else() and ifelse()

if() executes a command if the condition is TRUE

else() is usually used with an initial if(), and executes if TRUE

x <- 100
if(x > 10){
print(paste(x, "is greater than 10"))
}
x <- 9
if(x > 10){
print(paste(x, "is greater than 10"))
} else{
print(paste(x, "is not greater than 10"))
}

if(), else() and ifelse()

Same as previous example, different syntax

x <- 9

ifelse(test = x > 10,
       yes = print(paste(x, "is greater than 10")),
       no = print(paste(x, "is not greater than 10")))

for() example IRL

go to script…

problem

data <- data.frame(names=c('Tom', 'Bert', 'Anne'),
                   height = c(180, 188, 162),
                   country = c('England', 'Scotland', 'Wales'))
> data
  names height  country
1   Tom    180  England
2  Bert    188 Scotland
3  Anne    162    Wales

Use write.csv() to output each line to a csv file with the name of each file being the value of the ‘names’ vector(