S. O'Sullivan
S. O'Sullivan

Reputation: 45

Double Summation using for loop

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.

Upvotes: 2

Views: 2709

Answers (2)

Patrik_P
Patrik_P

Reputation: 3200

Given

x <- 3:5
y <- 2:3

you can approach it as

out <- integer()
for(i in x){
  for(j in y){
    out <- c(out, i*j)
  }
}
sum(out)

or, as the above accrues the vector (which might be expensive), alternatively

with(expand.grid(x, y), sum(Var1*Var2))

or

sum(x %o% y) which is another way for sum(outer(x,y))

Upvotes: 3

cremorna
cremorna

Reputation: 374

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

Upvotes: 2

Related Questions