The nrow Function in R (4 Examples)

 

Basic R Syntax:

nrow(data)

 

The nrow R function returns the number of rows that are present in a data frame or matrix. Above, you can find the R code for the usage of nrow in R.

You want to know more details? In this article, I’m going to provide you with several reproducible examples of typical applications of the nrow function in R.

 

Example 1: Count the Number of Rows of a Data Frame

For the following example, I’m going to use the iris data set. Load the data set:

data(iris)         # Load the iris data set
head(iris)         # Head of the iris data set

 

nrow function in R - Iris Example Data Frame

Table 1: Iris Data Frame as Example for the Application of nrow in R.

 

After loading the data frame in R, we can apply the nrow function as follows:

nrow(iris)         # Number of rows
# 150

The number of lines of the iris database is 150.

 

Example 2: Using nrow in R with Condition

Let’s assume we want to count the rows of the iris data set where the variable Sepal.Length is larger than 5. With the following R code, we can examine this condition:

nrow(iris[iris$Sepal.Length > 5, ])           # Number of lines that meet the condition
# 118

118 rows (i.e. observations) have a Sepal.Length larger than 5.

 

Example 3: nrow with NA or NULL

Often, your data will have missing values (usually labeled as NA or NULL). You want to know, how many complete rows are available in your data? The complete.cases function can help:

iris_miss <- iris                             # Duplicate data
iris_miss$Species[c(3, 17, 55, 127)] <- NA    # Insert some NA values to Species
nrow(iris_miss[complete.cases(iris_miss), ])  # Count number of complete rows
# 146

 

Example 4: For Loop Using nrow in R

In the next example, I’m showing you how to use the nrow R function as condition within a for loop – Probably the situation where I use nrow the most often.

Assume that we want to calculate the cumulative sum of the column Petal.Width:

cumsum_Petal.Width <- iris$Petal.Width[1]   # Create new vector object
 
for(i in 2:nrow(iris)) {                    # Use nrow as condition
  cumsum_Petal.Width[i] <-                  # Calculate cumulative sum
    cumsum_Petal.Width[i - 1] + iris$Petal.Width[i]
}
 
cumsum_Petal.Width                          # Print vector to RStudio console
# 0.2   0.4   0.6   0.8   1.0   1.4   1.7   1.9   2.1   2.2

Note: The cumulative sum could be calculated much easier with the cumsum R function. The for loop above is just for illustration.

 

Video Examples: nrow and Related Functions in Practice

In case you want to see more examples for the application of nrow in R, you may have a look at the following video of the YouTube channel of Richard Webster:

 

 

Further Reading

 



 

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu