How to Use nrow Function in R

The nrow function in R returns the number of rows in an R object, such as a matrix or data frame. It is useful for quickly obtaining the dimensions of a data set, as it can be used to determine the number of observations in a data set before performing any data manipulation or analysis. It is important to remember that nrow counts the number of rows in a data set, not the number of observations. Therefore, if any observations have been deleted, nrow will not account for those observations.


You can use the nrow() function in R to count the number of rows in a data frame:

#count number of rows in data frame
nrow(df) 

The following examples show how to use this function in practice with the following data frame:

#create data frame
df <- data.frame(x=c(1, 2, 3, 3, 5, NA),
                 y=c(8, 14, NA, 25, 29, NA)) 

#view data frame
df

   x  y
1  1  8
2  2 14
3  3 NA
4  3 25
5  5 29
6 NA NA

Example 1: Count Rows in Data Frame

The following code shows how to count the total number of rows in the data frame:

#count total rows in data frame
nrow(df)

[1] 6

There are 6 total rows.

Example 2: Count Rows with Condition in Data Frame

The following code shows how to count the number of rows where the value in the ‘x’ column is greater than 3 and is not blank:

#count total rows in data frame where 'x' is greater than 3 and not blank
nrow(df[df$x>3 & !is.na(df$x), ])

[1] 1

There is 1 row in the data frame that satisfies this condition.

Example 3: Count Rows with no Missing Values

The following code shows how to use the function to count the number of rows with no missing values in the data frame:

#count total rows in data frame with no missing values in any column
nrow(df[complete.cases(df), ])

[1] 4

There are 4 rows with no missing values in the data frame.

Example 4: Count Rows with Missing Values in Specific Column

#count total rows in with missing value in 'y' column
nrow(df[is.na(df$y), ])

[1] 2

There are 2 rows with missing values in the ‘y’ column.

x