0

I have the following data:

 State         Name Population
1    NY     New York          1
2    NJ   New Jersey          2
3    CA   California          1
4    RI Rhode Island          1
5    NY     New York          1

I want to use R to sum up the population column for all unique combination of the state and name columns. So the end result will be:

     State    Name        Population
1    NJ       New Jersey           2
2    NY       New York             2
3    CA       California           1
4    RI       Rhode Island         1

Any help is greatly appreciated!

2 Answers2

0

You can use dplyr package to do something like this:

library(dplyr)
df %>% group_by(State, Name) %>% summarise(Population = sum(Population))
Gopala
  • 10,363
  • 7
  • 45
  • 77
0

We can just use aggregate from base R

aggregate(Population~., df1, sum)

Or with data.table

library(data.table)
setDT(df1)[, list(Population = sum(Population)), .(State, Name)]
akrun
  • 874,273
  • 37
  • 540
  • 662