Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201894

Calculating a nested sum

$
0
0

I would like to compute in R something of the following kind:

formular

It is important that the summand could be any function f(y,x).

My approach so far is with nested for loops:

n <- 5
fun <- function(y,x){y^2 + sqrt(y*x)} # might be any function of y and x
sum_x <- c()
for(x in 1:n){
  sum_y <- c()
  for(y in 0:x){
    sum_y[y+1] <- fun(y,x)
  }
  sum_x[x] <- sum(sum_y)
}
sum(sum_x) # 147.6317

However, I do not like this approach. It's pretty ugly and becomes very inconvenient if lower and upper bound need to be more flexible. I thought about using expand.grid and then applying fun to it using mapply, but couldn't figure out how to express the nested structure of the sums. Any suggestions how to do this?


Viewing all articles
Browse latest Browse all 201894

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>