[R] sum portions of a vector

David Winsemius dwinsemius at comcast.net
Mon Dec 10 20:55:53 CET 2012


On Dec 10, 2012, at 11:29 AM, Sam Steingold wrote:

> How do I sum portions of a vector into another vector?
> E.g., for
> --8<---------------cut here---------------start------------->8---
>> vec <- 1:10
>> breaks <- c(3,8,10)
> --8<---------------cut here---------------end--------------->8---
> I want to get a vector of length 3 with content
> --8<---------------cut here---------------start------------->8---
> 6 = 1+2+3
> 30 = 4+5+6+7+8
> 19 = 9+10
> --8<---------------cut here---------------end--------------->8---
> Obviously, I could write a loop, but I would rather have a vectorized
> version.

 > split(vec, findInterval(seq_along(vec), breaks+.001, right=TRUE) )
$`0`
[1] 1 2 3

$`1`
[1] 4 5 6 7 8

$`2`
[1]  9 10

Needed to push the breaks slightly rightward since findInterval  
generally returns left-closed interval values.

-- 

David Winsemius
Alameda, CA, USA




More information about the R-help mailing list