0

I have a data set that resembles this:

> data
  Year X1 X2 X3
1 1990  1  0  0
2 1990  0  1  0
3 1991  0  0  0
4 1991  1  0  1
5 1991  1  1  1
6 1992  0  1  0

And I am trying to sum up X1, X2, and X3 by year, such that the end-result is:

> aggr_data
  Year X1 X2 X3
1 1990  1  1  0
2 1991  2  1  2
3 1992  0  1  0

I know that I can sum each column by year using dplyr:

aggr_data$X1 <- data %>%
  group_by(year) %>%
  summarise(sum.amount = sum(X1))

However, it is tedious to do it for every variable in my dataset, and even if I were to do so, the result is two lists of the year and the sum amounts, instead of a dataframe which I need.

Is there a way for me to simultaneously sum the columns by year, such that the end result is a dataframe comprising a year column and the summed amounts?

Thanks for your help!

taylor
  • 5
  • 2

0 Answers0