[R] sum portions of a vector

arun smartpink111 at yahoo.com
Mon Dec 10 21:54:33 CET 2012

May be this also helps:
do.call(rbind,lapply(split(vec,findInterval(vec,c(4,9))),function(x) paste0(sum(x),"=",paste(x,collapse="+"))))
#0 "6=1+2+3"     
#1 "30=4+5+6+7+8"
#2 "19=9+10"     

----- Original Message -----
From: Sam Steingold <sds at gnu.org>
To: r-help at r-project.org
Sent: Monday, December 10, 2012 2:29 PM
Subject: [R] sum portions of a vector

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

Sam Steingold (http://sds.podval.org/) on Ubuntu 12.04 (precise) X 11.0.11103000
http://www.childpsy.net/ http://palestinefacts.org http://ffii.org
http://jihadwatch.org http://www.PetitionOnline.com/tap12009/
One can find Holy Grail or Higgs boson, but not the second sock.

R-help at r-project.org mailing list
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