/var/logmarcus chiu

/var/log

❯

Computer

❯

Computer/Programming Languages

❯

Computer Languages - Mathematical/Statistical Programming Languages

❯

R

R - Control Statements

Created on Aug 19, 2021

  • if statement for conditional programming
  • if…else statement for conditional programming
  • for loop to iterate over a fixed number of iterations
  • while loop to iterate until a logical statement returns FALSE
  • repeat loop to execute until told to break
  • break/next arguments to exit and skip iterations in a loop

if

if (test_expression) { statement }

if else

if (test_expression) {
        statement 1
} else {
        statement 2
}

for loop

for(i in 1:100) {
        <do stuff here with i>
}

while loop

counter <- 1

while(test_expression) {
        statement
        counter <- counter + 1
}

repeat loop

counter <- 1

repeat {
        statement
        
        if(test_expression){
                break
        }
        counter <- counter + 1
}

break/next arguments

x <- 1:5

for (i in x) {
        if (i == 3){
                break
                }
        print(i)
}
## [1] 1
## [1] 2
x <- 1:5

for (i in x) {
        if (i == 3){
                next
                }
        print(i)
}
## [1] 1
## [1] 2
## [1] 4
## [1] 5