S. O&#39;Sullivan - 3 years ago 87
R Question

# double summation using for loop in R

I'm trying to do a double summation for a quite complicated formula in R, but I don't think the for loops are working as I'd expect.

Here's just a basic version of something for complicated I'm trying to do.

\sum_{i=3}^{5}\sum_{j=2}^{3} (i*j)

I'd hope this would sum all the terms together like 3*2+3*3+4*2+4*3+5*2+5*3
which would give 60. However the code I have doesn't produce that so wondering what R is actually doing with this double for loop.

 for(i in 3:5){
for(j in 2:3){
x<-i*j
}
}


I know this example is trivial but if I can understand this hopefully will be able to apply it to more complicated thing I'm trying to do.

Thank you!

You forgot to add x to each loop:

x <- 0
for(i in c(3,4,5)){
for(j in c(2,3)){
x <- x + i*j # add x here
}
}
x


EDIT: this is the same as what @G5W said

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download