Count Number of Rows by Group Using dplyr Package in R (Example)
In this R tutorial you’ll learn how to get the number of cases in each group.
The article contains these topics:
Let’s take a look at some R codes in action…
Introducing Example Data
As a first step, we’ll have to define some data that we can use in the examples below:
data <- data.frame(x1 = 1:10, # Example data x2 = letters[1:10], group = c("A", "A", "A", "B", "B", "B", "B", "C", "C", "D")) data # Show example data # x1 x2 group # 1 1 a A # 2 2 b A # 3 3 c A # 4 4 d B # 5 5 e B # 6 6 f B # 7 7 g B # 8 8 h C # 9 9 i C # 10 10 j D
The previous output of the RStudio console shows the structure of our example data – It consists of three columns, whereby one of these columns is specifying the group of each row.
Example: Find Number of Cases by Group Using group_by, summarise & n
install.packages("dplyr") # Install dplyr package library("dplyr") # Load dplyr
Now, we can use the group_by(), summarise() and n() functions to return a tibble containing all group counts:
data %>% # Count rows by group group_by(group) %>% summarise(n = n()) # # A tibble: 4 x 2 # group n # <fct> <int> # 1 A 3 # 2 B 4 # 3 C 2 # 4 D 1
As you can see based on the previous output of the RStudio console, group A has three cases, group B has four cases, group C has 2 cases, and group D has only 1 case.
Video & Further Resources
Do you need more information on the R code of this article? Then you might watch the following video of my YouTube channel. I’m explaining the R programming codes of this article in the video:
Furthermore, you could read the related articles of this website. Some posts are shown below.
- Count Number of Cases within Each Group of Data Frame
- Count Number of List Elements
- Count NA Values in R
- Numbering Rows within Groups of Data Frame
- nrow Function in R
- dplyr Package in R
- The R Programming Language
In summary: At this point of the post you should know how to count the number of rows within each group of a data frame in the R programming language. Let me know in the comments, if you have additional questions.