nrow in R: The number of rows in the R object

nrow in r

In this article, we will share with you the syntax, the usage, and how to perform the nrow in R. The nrow() function in R is used to count the number of rows in the R object. Let’s follow this article to learn more about the nrow in R with the definition and examples below.

What does the nrow do in R?

The nrow() function in R is used to help you count the number of rows in the vector, the array, the matrix, or the data frame. But, when the function is used for the vector or the array, the result is NULL. For this case, you should use the NROW() function instead. This function considers each element in the vector or the array as 1 row. So the result will be the size of the vector.

Syntax:

nrow(data)

NROW(data)

Parameters:

  • x: The vector, the array, the matrix, or the data frame.

How to use the nrow in R?

As you learn about the previous part, the nrow() function in R can help you find the number of rows in an object. Let’s learn how to use it with some examples below.

Perform the nrow function in the vector

The nrow() function will return NULL when you use it with the vector or the array.

Example:

# Create the vector
data <- c(7, 8, 5, 6, 4)
nrow(data)

Output

NULL

Let’s use the NROW() function with the previous data and see how the result changes.

Example:

data <- c(7, 8, 5, 6, 4)
NROW(data)

Output

[1] 5

When you use the NROW() function with the vector or the array, the result will be returned as the length of that object.

Find the number of rows in the data frame

You can use the nrow() function to find the number of rows in the data frame.

Look at the example below.

# Create the data frame
df <- data.frame(
    players = c("Bruno", "Rabiot", "Vinicius", "Foden", "Saka"),
    assists = c(4, 3, 3, 2, 2)
)

# Top 5 assists in World Cup 2022
df

Output

 players assists
1 Bruno    4
2 Rabiot   3
3 Vinicius 3
4 Foden    2
5 Saka     2

Let’s use the nrow() function to find the number of rows in this data frame.

df <- data.frame(
    players = c("Bruno", "Rabiot", "Vinicius", "Foden", "Saka"),
    assists = c(4, 3, 3, 2, 2)
)

nrow(df)

Output

[1] 5

As you can see, the result is also the size of each column in the data frame.

Find the number of rows in the matrix

You can use the nrow() function to find the number of rows in the matrix.

Look at the example below.

# Create a matrix
mat <- matrix(2:13, nrow = 3, ncol = 4)
nrow(mat)

Output

[1] 3

Summary

We have shown you the definition, the syntax, and how to perform the nrow in R. After learning this method, you can apply it to find the number of rows in the vector, the array, the matrix, or the data frame. We hope this article is useful for you. Thanks!

Maybe you are interested:

Posted in R

Leave a Reply

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