# Grouping data in ranges in R by summing them

I have data like this :

      year   nb
1     1901  208
2     1902  200
3     1903  223
4     1904  215
5     1905  187
6     1906  214


And I want to specify levels, such that I can summarize the data this way :

      years   nb
1     1901-1910  2082
2     1911-1920  6200


I had a hard time doing this either with group, aggregate, or encode until then. I found a very ugly way of doing that, like that :

sum(DF$nb[DF$year> 1901 & DF$year <= 1910])  But I would like to know if there is a more elegant way to do it. Sorry if my question is too basic, Xavier ## 2 Answers One option is to create a new variable for your bins with cut or cut2 in package Hmisc. dat <- data.frame(year = 1901:2000, value = runif(100)) dat <- transform(dat, bin = cut(year, 10))  I would then probably use plyr to do the group by summary: library(plyr) ddply(dat, "bin", summarize, totVal = sum(value))  The help page for cut should be illustrative in defining labels, what to do with edge cases (include / exclude min or max values), etc. • floor((year-1900)/10) will produce a factor to summarize over. – Alex Commented Aug 16, 2011 at 11:45 Interesting Chase. I hasn't seen transform and would have likely done it this (second) way: set.seed(1234) dat <- data.frame(year = 1901:2000, value = runif(100)) dat <- transform(dat, bin = cut(year, 10)) set.seed(1234) dat2 <- data.frame(year = 1901:2000, value = runif(100)) dat2$bin <- cut(dat$year, 10) identical(dat,dat2) # true  Following on from that I would look to: dat2$bin <- cut(dat\$year, 10, labels=F) # this gives you 1:10 as labels rather than the very messy 'intervals'
aggregate(value~bin, data=dat2, sum)

> aggregate(value~bin, data=dat2, sum)
bin    value
1    1 4.892264
2    2 4.546337
3    3 4.165217
4    4 4.733585
5    5 5.136625
6    6 4.530420
7    7 3.616002
8    8 3.864675
9    9 4.936536
10  10 3.328065

• check out with and within for cousins to transform. plyr adds summarize to the mix as well. Commented Aug 16, 2011 at 1:47