How to Use Nrow Function in R?
Last Updated :
19 Dec, 2021
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
data= data.frame (col1 = c (1,2,3,4),
col2 = c ( NA , NA , NA , NA ),
col3 = c (23,45,43, NA ))
print (data)
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
data = data.frame (col1 = c (1,2,3,4),
col2 = c ( NA , NA , NA , NA ),
col3 = c (23,45,43, NA ))
print (data)
print ( nrow (data[data$col1>3 & data$col3>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
data = data.frame (col1 = c (1,2,3,4),
col2 = c (89, NA , NA ,67),
col3 = c (23,45,43, NA ))
print (data)
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
data = data.frame (col1 = c (1,2,3,4),
col2 = c (89, NA , NA ,67),
col3 = c (23,45,43, NA ))
print (data)
print ( nrow (data[ is.na (data$col1), ]))
print ( nrow (data[ is.na (data$col2), ]))
print ( nrow (data[ is.na (data$col3), ]))
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...