View
205
Download
0
Category
Preview:
Citation preview
Loops in RSummer Data Jam
Type of Loops● For loop● While loop● ifelse● Repeat Nested For loop● Apply Function
For LoopUsed to iterate over a vector.
Iteration Mode● By value#Code Formatfor (val in sequence) { statement}
Example
Examplex <- c(2,5,3,9,8,11,6)for (val in x) { if(val %% 2 == 0) print(val)}
By Index
Format
for (i in 1:100) {print(i)
}
Exampledata <-read.csv(‘kalonzo’)
for (i in 1:nrow(data)){ print(data$text)[i]}
While Loop
Loop will execute a block of commands until the condition is no longer satisfied.
while (test_expression) { statement}
Example i <- 1
while (i < 6) { print(i) i = i+1}
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)
Examplex <- 1
repeat { print(x) x = x+1 if (x == 6){ break }}
Nested For Loop● Utilised for traversing multiple
dimensions in high-dimensional data.
● Executes outer loop first.
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
Recommended