onjalo
onjalo

Reputation: 13

How to summarize multiple rows in a single new row in r

I have a dataframe of states and certain population

# A tibble: 9 x 2
  region        selected_pop
  <chr>             <dbl>
1 Connecticut       59306
2 Maine             85416
3 Massachusetts     83870
4 New Hampshire     62250
5 New Jersey       533328
6 New York         197454
7 Pennsylvania      35732
8 Rhode Island      85614
9 Vermont            3414

and I want to create an output that looks like this, where totalpop is sum of population of each state. How would I do this in r?

region Totalpop
Northeast 1146384

Upvotes: 1

Views: 779

Answers (1)

akrun
akrun

Reputation: 887048

Assuming the dataset have only 'Northeast' states, an option is to change the 'region' to 'Northeast' in group_by and summarise the 'selected_pop'

library(dplyr)
df1 %>%
     group_by(region = 'Northeast') %>%
     summarise(Total_pop = sum(selected_pop))

Upvotes: 1

Related Questions