Hi guys,

Have the following problem computing vectors with pure vector algebra and end 
up reverting to recursion or for-looping. 

Function my_cumsum calculates a weighted average (W) of ratios (R), but only up 
to the given size/volume (v). Now I recurse into the vector (from left to 
right) with what you have left from the difference of volume minus current 
weight, and stop when the difference is less than or equal to the current 
weight. 

Vectors W and R have the same length, and v is always a positive integer.

W: {w_1 w_2 .. w_m}
R: {r_1 r_2 .. r_m}

my_cumsum <- function(v, R, W) {
        if (v <= W[1]) # check the head
                v*R[1]
        else
                W[1]*R[1] + my_cumsum(v - W[1], R[2:length(R)], W[2:length(W)]) 
# recurse the tail
}

Any help is greatly appreciated!

Fernando Alvarez

"Great ideas originate in the muscles." ~ Thomas A. Edison

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to