[R] sum portions of a vector

Marc Schwartz marc_schwartz at me.com
Mon Dec 10 22:02:00 CET 2012


On Dec 10, 2012, at 1:29 PM, Sam Steingold <sds at gnu.org> 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.
> Thanks!



See ?findInterval.

> findInterval(seq(along = vec), breaks + 1)
 [1] 0 0 0 1 1 1 1 1 2 2

> as.vector(sapply(split(vec, findInterval(seq(along = vec), breaks + 1)), 
                   sum))
[1]  6 30 19


Did you just want the above, or did you really want:

> as.vector(sapply(split(vec, findInterval(seq(along = vec), breaks + 1)), 
                   function(x) paste(sum(x), "=", paste(x, collapse = "+"))))
[1] "6 = 1+2+3"      "30 = 4+5+6+7+8" "19 = 9+10"   



Regards,

Marc Schwartz




More information about the R-help mailing list