← All languages
R function of the day
Random

nrow

Return the number of rows of a matrix, data frame, or array.

Description

nrow() returns the number of rows present in a matrix, data frame, or array. For a matrix or data frame, it returns the first dimension. It returns NULL for vectors that have no dim attribute, which distinguishes it from length().

nrow() is closely related to ncol(), which returns the number of columns. Together they are more readable alternatives to using dim(x)[1] and dim(x)[2] directly. The function NROW() (uppercase) is a safer variant that treats vectors as single-column matrices, returning the length for vectors instead of NULL.

Use nrow() to determine the size of data before processing, to set up loops or allocate storage, and to validate data dimensions. It is essential for writing robust functions that handle matrices and data frames of arbitrary size.

Arguments

NameDescriptionOptional
x A matrix, data frame, array, or any object with a dim attribute. No

Example

# Number of rows in a data frame
df <- data.frame(a = 1:5, b = letters[1:5])
nrow(df)
# [1] 5

# Number of rows in a matrix
m <- matrix(1:12, nrow = 3)
nrow(m)
# [1] 3

Reference