Search notes:

R function: for

for (i in seq(2, 8, 3)) {
  for (j in 1:i) {
    cat("* ")
  }
  cat("\n")
}
# * *
# * * * * *
# * * * * * * * *
Github repository about-r, path: /functions/for/for.R

Iterating over an ascending sequence of integers

Iterating over an ascending sequence of integers is particularly simple with a combination of for and colon operator.
for (i in 1:5) {
  cat (i, "\n")
}
# 1
# 2
# 3
# 4
# 5
Github repository about-r, path: /functions/for/sequence-of-integers.R

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
Github repository about-r, path: /functions/for/character-vector.R

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));
}
Github repository about-r, path: /functions/for/next.R

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
#
Github repository about-r, path: /functions/for/data-frame.R

See also

Index to (some) R functions

Index