neversaint
neversaint

Reputation: 64004

Multiplying Product Via Loop in R

I want to multiply all the element in the fact vector, namely:

final_prod = 0.01 * 0.05 * 0.02

This is how I do it in loop.

fact <- c(0.01,0.05,0.02)

final_prod <- 1;
for (i in 1:range(fact)){
   all_prod <- all_prod * fact[i];
}

print(final_prod)

But the final product it gave is wrong. It should be 0.00001 instead of 0.01.

What's wrong with my approach above?

I understand there is R'ish way. But the reason I want to do it in loop is because there is more complex computation involved.

Upvotes: 1

Views: 4250

Answers (2)

IRTFM
IRTFM

Reputation: 263342

The range function returns a two element vector and the ":" dyadic operator is only taking the first one. So you are getting 1:0.01 which is just 1 and then a single term product fact[1]. You could have used,

for (i in fact) {all_prod <- all_prod * i } 

...although David Robinson has already shown you how to use prod more economically:

Upvotes: 2

David Robinson
David Robinson

Reputation: 78600

  1. Rather than range, you want 1:length(fact).

  2. You are switching between the variables final_prod and all_prod, such that all_prod is never defined at the start.

  3. Why don't you want to do this the R way, which takes less code? However complicated the computation involved is, it's probably possible (you could try explaining it here), but for this you would just use the function prod:

    final_prod = prod(fact)
    

Upvotes: 6

Related Questions