German Romero Acevedo
German Romero Acevedo

Reputation: 51

How to find the number of rows in a grouped data frame with a given condition

I have a data frame and I need to find the number of rows of a group with a given condition. For Example I have:

C1|C2|
------  
A1| T
------
A1| T
------
B1| T
------
A1| F
-----
B1| F

I am trying somthing like

df %>% group_by(C1) %>%
       summarise(n_condition = n(C2 == T))

To get:

C1|n_condition|
---------------
A1|     2     |
--------------|
B1|     1     |
--------------|

Thanks for your help

Upvotes: 0

Views: 18

Answers (1)

Karthik S
Karthik S

Reputation: 11584

Does this work:

library(dplyr)
df %>% group_by(C1) %>% summarise(n_condition = sum(C2 == 'T'))
# A tibble: 2 x 2
  C1    n_condition
  <chr>       <int>
1 A1              2
2 B1              1

Upvotes: 1

Related Questions