Open In App

How to Use Nrow Function in R?

Last Updated : 19 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to use Nrow function in R Programming Language. This function is used in the dataframe or the matrix to get the number of rows.

Syntax: nrow(data)

where, data can be a dataframe or a matrix.

Example 1: Count Rows in Data Frame

In this example, we are going to count the number of rows in the dataframe.

R




# create a dataframe with 4 rows 
# and 3 columns
data=data.frame(col1 = c(1,2,3,4),
                col2 = c(NA,NA,NA,NA),
                col3 = c(23,45,43,NA))
  
# display
print(data)
  
# count the number of rows
print(nrow(data))


Output:

Example 2: Count Rows with Condition in Data Frame

Here we are going to specify the condition inside the nrow() function.

Syntax: nrow(data[condition, ])

where,

  • data is the input dataframe
  • condition is used to get the rows.

R




# create a dataframe with 4 rows and 3 columns
data = data.frame(col1 = c(1,2,3,4),
                  col2 = c(NA,NA,NA,NA),
                  col3 = c(23,45,43,NA))
  
# display
print(data)
  
# count the number of rows 
# with condition column1 is greater than
# 3 and column3 is greater than 25
print(nrow(data[data$col1>3 & data$col3>25, ]))
  
# count the number of rows 
# with condition column1 is greater than 3
# or column3 is greater than 25
print(nrow(data[data$col1>3 | data$col3>25, ]))


Output:

Example 3: Count Rows with no Missing Values

Here we are going to get the total number of rows with no missing values by using complete.cases()  inside the nrow method.

Syntax: nrow(data[complete.cases(data), ])

R




# create a dataframe with 4 rows and 3 columns
data = data.frame(col1 = c(1,2,3,4),
                  col2 = c(89,NA,NA,67),
                  col3 = c(23,45,43,NA))
  
# display
print(data)
  
# total rows in dataframe  with no missing values
print(nrow(data[complete.cases(data), ]))


Output:

Example 4: Count Rows with Missing Values in Specific Column

Here, we are going to count the number of missing rows in a particular column using is.na() method.

Syntax: nrow(data[is.na(data$column_name), ])

where, 

  • data is the input dataframe
  • column_name is the column to get missing value count

R




# create a dataframe with 4 rows and
# 3 columns
data = data.frame(col1 = c(1,2,3,4),
                  col2 = c(89,NA,NA,67),
                  col3 = c(23,45,43,NA))
  
# display
print(data)
  
# total rows in dataframe 
# with no missing values in column1
print(nrow(data[is.na(data$col1), ]))
  
# total rows in dataframe 
# with no missing values in column2
print(nrow(data[is.na(data$col2), ]))
  
# total rows in dataframe 
# with no missing values in column3
print(nrow(data[is.na(data$col3), ]))


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads