Search code examples
rdataframemerging-data

How to combine data points in a data frame in R?


The data frame x has a column in which the values are periodic. For each unique value in that column, I want to calculate summation of the second column. If x is something like this:

x <- data.frame(a=c(1:2,1:2,1:2),b=c(1,4,5,2,3,4))
  a b
1 1 1
2 2 4
3 1 5
4 2 2
5 1 3
6 2 4

The output I want is the following data frame:

a b
1 9 
2 10

Solution

  • Using aggregate as follows will get you your desired result

    aggregate(b ~ a, x, sum)