Reputation: 111
I want to compute the following term in R, but without using loops ("for" cycles):
So far, I already calculated it manually and tried to use sequence functions for both index variables i and j and integrated them in a cumsum function and summed up the returning vector.
i <- seq(1:10)
j <- seq(1:5)
sum(cumsum((i^5)/(10+j^i)))
However, the results do not match with my manual calculation, so this seems to be a wrong approach. Could anybody help me out on this?
Upvotes: 3
Views: 294
Reputation: 101327
Try outer
> sum(outer(1:10, 1:5, FUN = function(i,j) i^5/(10+j^i)))
[1] 20845.76
Upvotes: 4
Reputation: 7818
Given
i <- seq(1:10)
j <- seq(1:5)
Solution 1:
ir <- rep(i, each = length(j))
jr <- rep(j, length(i))
sum(ir^5 / (10 + jr^ir))
#> [1] 20845.76
Solution 2:
d <- expand.grid(i=i,j=j)
with(d, sum(i^5 / (10 + j^i)))
#> [1] 20845.76
Solution 3: (@jogo)
sum(sapply(i, function(i) i^5 / (10+j^i)))
#> [1] 20845.76
Upvotes: 3