for
A “for” loop can be used for iterating over the items of any vector/matrix/table.
Syntax
for(s in X){
statements
}
Details
As in “if-else”, the parentheses after “for” are required. If more than one statement are to be executed in case a condition is true, we must specify a block of statements with braces { }. Otherwise the braces are optional.
X is a pair/vector/matrix/table. It loops over a matrix column by column, and it loops a table row by row. When looping over a matrix, each column is represented as a vector; when looping over a table, each row is presented as a dictionary with column names as keys and cell values as values.
Examples
Looping over a pair:
$ for(s in 2:4){print s};
2
3
$ for(s in 4:1) print s;
3
2
1
Looping over a vector:
$ x=4 0 1 3;
$ for(s in x) print s;
4
0
1
3
Looping over a matrix: column by column.
$ m=1..6$3:2;
$ m;
#0 |
#1 |
---|---|
1 |
4 |
2 |
5 |
3 |
6 |
$ for(s in m){print s};
[1,2,3]
[4,5,6]
Looping over a table: row by row.
$ x = 1 2 3
$ y = 4 5 6
$ t = table(x,y)
$ for(s in t) print s;
y->4
x->1
y->5
x->2
y->6
x->3