Question

I am attempting to work with two columns using R.

I want to be able to groupBy column 1, but total the value 2.

col1 col2
A    3
B    2
A    5
B    1
B    4

Example result should be:

A    8
B    7

I have looked at "aggregate", "summaryBy", and "by" both, but I am missing something because I am not getting the desired output.

Any help would be appreciated...

Was it helpful?

Solution 2

Package data.table is your friend!

More info on http://datatable.r-forge.r-project.org/

library(data.table)
dt <- data.table(your_dataframe,key="col1")
dt[,list(col2=sum(col2)),by="col1" ]

OTHER TIPS

Consider your data is called dat then use aggregate, it worked for me

> aggregate(.~col1, FUN="sum", data=dat )
  col1 col2
1    A    8
2    B    7

For further examples see this post

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top