ncol()

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

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

Syntax

ncol(x)

Parameters

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

Examples

Basic usage with a matrix

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

Working with data frames

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

ncol(df)
# [1] 3

Using with NULL and vectors

ncol(NULL)
# NULL

vec <- 1:10
ncol(vec)
# NULL

Common Patterns

Loop over columns

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

for (j in 1:ncol(mat)) {
  print(sum(mat[, j]))
}

Check if object has columns

has_cols <- function(x) {
  !is.null(ncol(x))
}

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

has_cols(1:10)
# [1] FALSE

Get last column

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

mat[, ncol(mat)]
# [1]  3  6  9 12

See Also