-1

I have the following table structure:

Number      Type      Year
------      ----      ---- 
10          a         2000
20          b         2000
20          b         2000
10          c         2001

where I want to merge the results of cells where the column flag is the same. For example the two cells for type b, have two separate results, 20 and 20, both in the same year. I would like to end up with a data frame like this:

Number      Type      Year
------      ----      ---- 
10          a         2000
40          b         2000
10          c         2001

I can only seem to "melt" columns together at the moment. Can anyone help?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
brucezepplin
  • 9,202
  • 26
  • 76
  • 129
  • Please help us help you by providing us with a reproducible example (i.e. code and example data), see http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example for details. – Paul Hiemstra Sep 16 '13 at 12:34

3 Answers3

1
aggregate(yourdata$Number,by=list(Type=yourdata$Type,Year=yourdata$Year),sum)
dayne
  • 7,504
  • 6
  • 38
  • 56
1

Using a formula:

aggregate(Number ~ Type + Year, data=DF, sum)
Ferdinand.kraft
  • 12,579
  • 10
  • 47
  • 69
1

Solution using plyr package and data.table package:

library(plyr)
ddply(df,.(Type,Year),summarize, Number=sum(Number))

library(data.table)
DT<-data.table(df)
setkey(DT,Type,Year)
DT[,list(Number=sum(Number)),by="Type,Year"]
Metrics
  • 15,172
  • 7
  • 54
  • 83