Let’s say I have this vector
v <- c(1:100)
And I want to get this:
b[1] = sum (v[c(1:10)])
b[2] = sum (v[c(11:20)])
...
...
I can do a loop to solve this, but I am pretty sure there is a “R way” that should be something like:
b <- groupedSum(v, 10)
where b will be a vector which will have each group of 10 summed
What is the R way?
If there were NA’s in there you might need to add na.rm=TRUE to the argument list after
sum.Comments: I think Tyler’s approach is more complete because it provided better documentation. It suffers from needing to work around the vagaries of the
cut()function which I have always felt had the wrong defaults. In order to create a grouping that captures all of 1:100 he needs to use a 101 element vector. But that’s not Tyler’s fault. Send him any further votes, his answer is better.If gsk can use by-objects without running into class difficulties, he’s a better man than I. The output looks like a list but it’s really something different. Using his example:
I think by-objects are sort of like named vectors and sort of like matrices but the failure to inherit matrix class has always confused the heck out of me.