How to Use nrow Function in R (With Examples)


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 complete.cases() 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

The following code shows how to use the is.na() function to count the number of rows that have a missing value in the ‘y’ column specifically:

#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.

Additional Resources

How to Use rowSums() Function in R
How to Apply Function to Each Row in Data Frame in R
How to Remove Rows from Data Frame in R Based on Condition

Leave a Reply

Your email address will not be published.