[R] accumulate() function in R?

arun smartpink111 at yahoo.com
Sun Sep 15 17:25:05 CEST 2013


Hi,


If you have a vector of values to compare:
thresh1<- c(30,4,12,65,5)
indx<-findInterval(thresh1-1,cumsum(X))
indx2<-ave(rep(indx,indx),rep(indx,indx),FUN=seq)
 X[indx2]
# [1]  1  3  4  5  8  1  1  3  4  1  3  4  5  8 15  1  3
#you can split this into a list

split(X[indx2],cumsum(c(TRUE,diff(indx2)<=0)))
#$`1`
#[1] 1 3 4 5 8
#
#$`2`
#[1] 1
#
#$`3`
#[1] 1 3 4
#
#$`4`
#[1]  1  3  4  5  8 15
#
#$`5`
#[1] 1 3

A.K.



----- Original Message -----
From: "gildororonar at mail-on.us" <gildororonar at mail-on.us>
To: r-help at r-project.org
Cc: 
Sent: Saturday, September 14, 2013 10:36 PM
Subject: [R] accumulate() function in R?

I came from Python, newly learning R. is there something like  
accumulate() in R?

Example:
accumulate([1,2,3,4,5]) --> 1 3 6 10 15

Or perhaps I should show the problem. The problem I am trying to  
solve, is to select elements from X until it accumulate to 30. My  
solution is:

> X = c(1,3,4,5,8,15,35,62,78,99)
> X[sapply(seq_len(length(X)), function(x) { sum(X[1:x])}) < 30]
[1] 1 3 4 5 8

Is this already the shortest/canonical way to do it in R?


-------------------------------------------------

VFEmail.net - http://www.vfemail.net
$14.95 ONETIME Lifetime accounts with Privacy Features!  
15GB disk! No bandwidth quotas!
Commercial and Bulk Mail Options!

______________________________________________
R-help at 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.




More information about the R-help mailing list