How do you properly write a double for loop in R?
For example, in C I would do
int i, j;
for (i = 1; i < 6; i++) {
for (j=i; j <= 3; j++) {
printf("%i,%i\n",i,j);
}
// Do more operations for i > 3...
}
which would generate the (artificial) sequence:
1,1
1,2
1,3
2,2
2,3
3,3
In R you do not get the same behaviour when you write
for (i in 1:6) {
for (j in i:3) {
print(paste(i,j,sep=","))
}
}
so I've been reduced to doing something like
for (i in 1:6) {
j <- i
while (j <= 3) {
print(paste(i,j,sep=","))
j <- j+1
}
}
Is there a better way?
As Shane mentioned, maybe I should make this clear: I am particularly interested in the code-style matching the mathematics to make it easier for students to understand. It seems that students are the most comfortable with "for" loops.
In particular, I want my students to simulate a LIBOR market model. The dynamics of the forward rate are to be simulated under the same probability measure. As such, for each time step and each forward rate, the appropriate drift correction \mu_i needs to be calculated and added.