for (i in c(1:3, 5, 10)) {
writeLines(paste0("i=",i,", i*2=",i*2))
}
i=1, i*2=2
i=2, i*2=4
i=3, i*2=6
i=5, i*2=10
i=10, i*2=20
Department of Mathematics
University of Manitoba*
for
loopsfor
applies to lists or vectors
i=1, i*2=2
i=2, i*2=4
i=3, i*2=6
i=5, i*2=10
i=10, i*2=20
while
loopsrepeat
loopsif
statementsEven if list of stuff to do
is a single instruction, better to use curly braces
ifelse
statementsVery useful to set values based on simple tests
break
statement
break
breaks out of afor
,while
orrepeat
loop; control is transferred to the first statement outside the inner-most loop
next
statement
next
halts the processing of the current iteration and advances the looping index
Both
break
andnext
apply only to the innermost of nested loops