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

This Example shows how to return a group counter using the dplyr package. First, we have to install and load the dplyr package:

```install.packages("dplyr")        # Install dplyr package

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

Furthermore, you could read the related articles of this website. Some posts are shown below.

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.

Subscribe to the Statistics Globe Newsletter