Count Number of Rows in R
-
Use the
data.frame(table())
Function to Count Number of Rows in R -
Use the
count()
Function to Count Number of Rows in R -
Use the
ddply()
Function to Count Number of Rows in R

In real-life examples, we encounter large datasets containing hundreds and thousands of rows and columns. To work on such large chunks of data, we need to be familiar with the rows, columns, and data types.
This tutorial will introduce how to count the number of rows by group in R.
Use the data.frame(table())
Function to Count Number of Rows in R
The data.frame(table())
function creates a table with the count of different factor values. It counts the total unique rows of a column. We can easily pass the required column of the DataFrame to the function. See the following code snippet.
df <- data.frame(Name = c("Jack","Jay","Mark","Sam"),
Month = c("Jan","Jan","May","July"),
Age = c(12,10,15,13))
data.frame(table(df$Month))
Output:
Var1 Freq
1 Jan 2
2 July 1
3 May 1
Use the count()
Function to Count Number of Rows in R
The plyr
library in R performs basic data manipulation tasks like splitting data, performing some function, and merging it afterward. It has a function count()
which returns the frequency of unique rows of a DataFrame. We have to pass the DataFrame and column name as its parameter, as shown below:
df <- data.frame(Name = c("Jack","Jay","Mark","Sam"),
Month = c("Jan","Jan","May","July"),
Age = c(12,10,15,13))
library(plyr)
count(df, "Month")
Output:
Month freq
1 Jan 2
2 July 1
3 May 1
Use the ddply()
Function to Count Number of Rows in R
Another interesting function provided in the plyr
library is the ddply()
function. It splits the data into a subset, specifies some function to be applied to the data, and combine the result. In the example below, we will pass the DataFrame and column name to the function and the nrow
function as parameters:
df <- data.frame(Name = c("Jack","Jay","Mark","Sam"),
Month = c("Jan","Jan","May","July"),
Age = c(12,10,15,13))
library(plyr)
ddply(df, .(Month), nrow)
Output:
Month V1
1 Jan 2
2 July 1
3 May 1
Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.
LinkedInRelated Article - R Data Frame
- Delete Multiple Columns in R
- Get the Number of Columns in R
- Create Empty Data Frame in R
- Remove Rows With NA in One Column in R
- Remove Duplicate Rows by Column in R
- Create a Large Data Frame in R