nrow()

nrow(x)
Returns: integer | NULL · Updated March 13, 2026 · Base Functions
matrix dimensions data-frame base

nrow() returns the number of rows in a matrix, array, or data frame. It returns NULL for atomic vectors since vectors have no dimensions.

Syntax

nrow(x)

Parameters

ParameterTypeDefaultDescription
xmatrix, array, data frame, or NULLInput object to get row count from

Examples

Basic usage with a matrix

# Create a 3x4 matrix
mat <- matrix(1:12, nrow = 3, ncol = 4)
nrow(mat)
# [1] 3

Working with data frames

df <- data.frame(
  name = c("Alice", "Bob", "Charlie"),
  age = c(25, 30, 35),
  score = c(85, 92, 78)
)

nrow(df)
# [1] 3

Using with NULL and vectors

# NULL has no dimensions
nrow(NULL)
# NULL

# Vectors have no dimensions
vec <- 1:10
nrow(vec)
# NULL

Common Patterns

Loop over rows

mat <- matrix(1:12, nrow = 3)

# Process each row
for (i in 1:nrow(mat)) {
  print(mean(mat[i, ]))
}

Check if object has rows

has_rows <- function(x) {
  !is.null(nrow(x))
}

has_rows(matrix(1:4, 2, 2))
# [1] TRUE

has_rows(1:10)
# [1] FALSE

Get last row

mat <- matrix(1:12, nrow = 3, ncol = 4)

# Get last row
mat[nrow(mat), ]
# [1]  9 10 11 12

See Also