How to Count Number of Rows in R (With Examples)


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

#count total rows in data frame
nrow(df)

#count total rows with no NA values in any column of data frame
nrow(na.omit(df))

#count total rows with no NA values in specific column of data frame 
nrow(df[!is.na(df$column_name),])

The following examples show how to use the nrow() function in practice.

Example 1: Count Total Number of Rows

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

#create data frame
df <- data.frame(var1=c(1, 3, 3, 4, 5),
                 var2=c(7, 7, 8, 6, 2),
                 var3=c(9, 9, 6, 6, 8),
                 var4=c(1, 1, 2, 8, 9))

#view data frame
df

  var1 var2 var3 var4
1    1    7    9    1
2    3    7    9    1
3    3    8    6    2
4    4    6    6    8
5    5    2    8    9

#count total rows in data frame
nrow(df)

[1] 5

There are 5 total rows in this data frame.

Example 2: Count Rows with No NA Values in Any Column

The following code shows how to count the total number of rows in a data frame with no NA values in any column:

#create data frame
df <- data.frame(var1=c(1, 3, 3, 4, 5),
                 var2=c(7, 7, 8, NA, 2),
                 var3=c(9, 9, NA, 6, 8),
                 var4=c(1, 1, 2, 8, 9))

#view data frame
df

  var1 var2 var3 var4
1    1    7    9    1
2    3    7    9    1
3    3    8   NA    2
4    4   NA    6    8
5    5    2    8    9

#count total rows in data frame with no NA values in any column of data frame
nrow(na.omit(df))

[1] 3

There are 3 total rows in this data frame that have no NA values in any column.

Example 3: Count Rows with No NA Values in Specific Column

The following code shows how to count the total number of rows in a data frame with no NA values in any column:

#create data frame
df <- data.frame(var1=c(1, 3, 3, 4, 5),
                 var2=c(7, 7, 8, NA, 2),
                 var3=c(9, NA, NA, 6, 8),
                 var4=c(1, 1, 2, 8, 9))

#view data frame
df

  var1 var2 var3 var4
1    1    7    9    1
2    3    7   NA    1
3    3    8   NA    2
4    4   NA    6    8
5    5    2    8    9

#count total rows in data frame with no NA values in 'var2' column of data frame
nrow(df[!is.na(df$var2),])

[1] 4

There are 4 total rows in this data frame that have no NA values in the ‘var2’ column.

Additional Resources

How to Remove Rows with NA in One Specific Column in R
How to Drop Rows that Contain a Specific String in R
How to Remove Duplicate Rows in R

Leave a Reply

Your email address will not be published.