Search notes:
R function: for
for (i in seq(2, 8, 3)) {
for (j in 1:i) {
cat("* ")
}
cat("\n")
}
# * *
# * * * * *
# * * * * * * * *
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
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
#
Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78
Stack trace:
#0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array)
#1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1740536865, '3.19.217.248', 'Mozilla/5.0 App...', NULL)
#2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/R/functions/for(123): insert_webrequest()
#3 {main}
thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78