Skip to content
Prev 285314 / 398502 Next

sequential sum

On Feb 14, 2012, at 1:38 PM, Nordlund, Dan (DSHS/RDA) wrote:

            
I had exactly that concern so tested my solution, which was a bit  
different than yours:

test <- c(1,2,3,4,10, 5);
test2 <- c(3,5,6,7,2,8,8,4,4);
test3 <- c(10,20,30,40, 50, 60);
tmp <- 0;
for (i in 1:length(test)){
tmp[i] <- sum(test3[which(test[1:i] %in% test2)]);
}

 > tmp
[1]   0  20  50  90  90 150
 > tmp2 <- ifelse(test %in% test2, cumsum(test3[test %in% test2]), 0)
 > tmp2
[1]   0  50  90 150   0  50  # was going to throw away.


 > tmp3 <- cumsum(ifelse(test %in% test2, test3, 0))
 > tmp3
[1]   0  20  50  90  90 150

So yours is better at spanning the non-match entries in the same  
manner as the for-loop.
David Winsemius, MD
West Hartford, CT