Why can't you just add columns instead?
colSums(my.data2[, 4:7])
or
library(plyr) numcolwise(sum)(my.data2) year county.a county.b county.c county.d 1 6030 510 422 334 246 >
However, if you want to reorganize, there are many options. The reshape2 package provides a nice syntax:
library(reshape2) > my.data.melt <- melt(my.data2, id.vars=c('units', 'year', 'landuse')) > my.data.melt units year landuse variable value 1 acres 2010 apple county.a 0 2 acres 2010 pear county.a 10 3 acres 2010 peach county.a 500 4 acres 2010 apple county.b 2 5 acres 2010 pear county.b 20 6 acres 2010 peach county.b 400 7 acres 2010 apple county.c 4 8 acres 2010 pear county.c 30 9 acres 2010 peach county.c 300 10 acres 2010 apple county.d 6 11 acres 2010 pear county.d 40 12 acres 2010 peach county.d 200
Then I would use plyr :
> library(plyr) > ddply(my.data.melt, .(variable), summarise, all.fruit=sum(value)) variable all.fruit 1 county.a 510 2 county.b 422 3 county.c 334 4 county.d 246 >
You can also do this using the R aggregate base or the data.table package.
data.table
> library(data.table) > my.data.melt <- as.data.table(melt(my.data2, id.vars=c('units', 'year', 'landuse'))) > my.data.melt[,list(all.fruit = sum(value)), by = variable] variable all.fruit 1: county.a 510 2: county.b 422 3: county.c 334 4: county.d 246
or if you want it to stay in wide format
> DT <- as.data.table(my.data2) > DT[, lapply(.SD, sum, na.rm=TRUE), .SDcols = grep("county",names(DT))]) county.a county.b county.c county.d 1: 510 422 334 246 # NB: This needs v1.8.3. Before that, an as.data.table() call was required as # the lapply(.SD,...) used to return a named list in this no grouping case.
aggregate
> aggregate(value~variable, my.data.melt, sum) variable value 1 county.a 510 2 county.b 422 3 county.c 334 4 county.d 246