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.
Rather than
range, you want1:length(fact).You are switching between the variables
final_prodandall_prod, such thatall_prodis never defined at the start.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: