On Dec 10, 2012, at 1:29 PM, Sam Steingold <s...@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 ______________________________________________ R-help@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.