17
Loops in R Summer Data Jam

Loops in R

Embed Size (px)

Citation preview

Page 1: Loops in R

Loops in RSummer Data Jam

Page 2: Loops in R

Type of Loops● For loop● While loop● ifelse● Repeat Nested For loop● Apply Function

Page 3: Loops in R

For LoopUsed to iterate over a vector.

Page 4: Loops in R

Iteration Mode● By value#Code Formatfor (val in sequence) { statement}

Page 5: Loops in R

Example

Page 6: Loops in R

Examplex <- c(2,5,3,9,8,11,6)for (val in x) { if(val %% 2 == 0) print(val)}

Page 7: Loops in R

By Index

Page 8: Loops in R

Format

for (i in 1:100) {print(i)

}

Page 9: Loops in R

Exampledata <-read.csv(‘kalonzo’)

for (i in 1:nrow(data)){ print(data$text)[i]}

Page 10: Loops in R

While Loop

Loop will execute a block of commands until the condition is no longer satisfied.

Page 11: Loops in R

while (test_expression) { statement}

Page 12: Loops in R

Example i <- 1

while (i < 6) { print(i) i = i+1}

Page 13: Loops in R

Repeat● 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.● We must ourselves put a condition explicitly

inside the body of the loop.● Use the break to terminate loop.● Otherwise produces an infinite loop.● Similar to while(True)

Page 14: Loops in R

Examplex <- 1

repeat { print(x) x = x+1 if (x == 6){ break }}

Page 15: Loops in R

Nested For Loop● Utilised for traversing multiple

dimensions in high-dimensional data.

● Executes outer loop first.

Page 16: Loops in R
Page 17: Loops in R

Apply FunctionA group of functions that internally implement loops.

apply: Function to process array marginslapply: Loop for a list, to evaluate a function on elementsapply: Similar to lapply but for simple output format.tapply: function to process vector subsets