How to Count Number of Rows in R

To count the number of rows in R, you can use the nrow()” function.

Example 1: Counting the total number of rows

Using the nrow() function to count number of rows

df <- data.frame(
  col1 = c(1, 2, 3),
  col2 = c(4, 5, 6),
  col3 = c(7, 8, 9)
)

nrow(df)

Output

[1] 3

Example 2: Counting rows, excluding rows with NA values

Counting rows excluding rows with NA values

To count the number of rows in a data frame that has no missing values (for example. No NA values) in any of the columns, use the na.omit() function in combination with the nrow() function.

df <- data.frame(
  col1 = c(1, 2, 3),
  col2 = c(4, NA, 6),
  col3 = c(7, 8, NA)
)

df

cat("----Counting rows while excluding rows with NA values----", "\n")

nrow(na.omit(df))

Output

Output of Counting rows with No NA values in any column

Example 3: Counting rows while excluding NA Values in a specific column

df <- data.frame(
  col1 = c(1, 2, 3),
  col2 = c(4, NA, NA),
  col3 = c(7, 8, 9)
)

nrow(df[!is.na(df$col2), ])

Output

[1] 1

That’s it!

Leave a Comment