-3

I'm trying to get a count of rows grouped by a certain variable using dplyr.

Example of the data below

enter image description here

Get a count of eunits = 0 by state.

Code that does not work:

data  %>% select(state, eunit) %>% filter(eunit == 0) %>% summarise(nrow(.)) %>% group_by(state)

Error that comes up:

Error in grouped_df_impl(data, unname(vars), drop)

zx8754
  • 52,746
  • 12
  • 114
  • 209
Jordan
  • 1,415
  • 3
  • 18
  • 44

2 Answers2

1

You need to reverse the order of group_by and summarise dplyr verbs. Also I'm not 100% sure that nrow(.) will work (it might, but I'm not in a placed to confirm). I typically use n() to count rows in a summarise verb.

data  %>% 
  select(state, eunit) %>% 
  filter(eunit == 0) %>% 
  group_by(state) %>%
  summarise(cnt = n()) 
R Thomas
  • 156
  • 6
0

You need to group by state first, then summarize and count:

data  %>% select(state, eunit) %>% filter(eunit == 0) %>% group_by(state) %>% summarise(n())
waskuf
  • 415
  • 2
  • 4