Iterating over a character vector
With
for
, it's (of course) also possible to iterate over a character
vector.
for (t in c('foo', 'bar', 'baz')) {
print(paste('t =', t));
}
#
# t = foo
# t = bar
# t = baz
Skipping iteration for specific elements with next
next
can be used to skip (or jump out of) an iteration:
for (v in -3:3) {
if (v == 0) next;
print(paste('12 /', v, '=', 12/v));
}
Iterating over a data frame
If
for()
is used to iterate over a
data frame (
for (col in df)) …
), in each iteration,
col
is set to the vectors that make up the columns in the data frame.
df <- data.frame(
col_one = c( 1 , 2 , 3 ),
col_two = c('one', 'two', 'three')
);
for (col in df) {
print('Iterating over a column (vector) of df');
for (cell in col) {
print(paste(' ', cell));
}
}
#
# Iterating over a column (vector) of df
# 1
# 2
# 3
# Iterating over a column (vector) of df
# one
# two
# three
#