0

I have a data frame with multiple y values for each x value. I'd like to create a new data frame from this one that only has one row for each x value, adding together all of the values for y and z that are associated with each x.

x   y   z
0   0   0
0   1   0
0   0   0
1   2   0
1   0   1
1   0   1
2   0   2
2   1   1
2   2   0
2   0   2
3   1   2
3   1   3

This is what I want the result to look like:

x   y   z
0   1   0
1   2   2
2   3   5
3   2   5

Is it possible to do this using cumsum, somehow conditionally on x? Thanks.

Andrew
  • 35
  • 4

1 Answers1

1

We can use aggregate from base R to group by 'x' and get the sum of other columns

aggregate(.~ x, df1, sum)
#  x y z
#1 0 1 0
#2 1 2 2
#3 2 3 5
#4 3 2 5
akrun
  • 874,273
  • 37
  • 540
  • 662