dim()
dim(x) dim() returns the dimensions of an array, matrix, or data frame. If the object does not have dimensions, dim() returns NULL. You can also use dim() to set dimensions on a vector, effectively converting it into a matrix or array.
Syntax
dim(x)
dim(x) <- value
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
x | any R object | none | An R object such as matrix, data frame, array, or vector |
value | integer vector | none | A numeric vector specifying the new dimensions |
Examples
Getting dimensions of a matrix
# Create a 3x4 matrix
m <- matrix(1:12, nrow = 3, ncol = 4)
dim(m)
# [1] 3 4
The matrix example shows dim() on a basic 3×4 numeric matrix. The same function works identically on data frames because both are rectangular structures with explicit row and column dimensions. Data frames containing mixed column types — character names, numeric ages, and numeric scores — are closer to what you encounter in everyday data analysis workflows.
Getting dimensions of a data frame
# Create a sample data frame
df <- data.frame(
name = c("Alice", "Bob", "Charlie"),
age = c(25, 30, 35),
score = c(85, 92, 78)
)
dim(df)
# [1] 3 3
Beyond retrieving dimensions, you can assign dimensions to reshape objects. This creates a bridge between vectors and matrices: a flat vector carries no dim attribute at all, but assigning one makes R interpret the vector as a matrix laid out in column-major order — each column is filled top-to-bottom before moving to the next column.
Setting dimensions on a vector
# Convert a vector into a matrix
vec <- 1:12
dim(vec) <- c(3, 4)
vec
# [,1] [,2] [,3] [,4]
# [1,] 1 4 7 10
# [2,] 2 5 8 11
# [3,] 3 6 9 12
After setting dimensions, it is often useful to test whether an object currently has a dim attribute. Vectors return NULL from dim(), so pairing dim() with is.null() provides a clean pattern for distinguishing 1D structures from matrices and arrays. This is helpful inside generic functions that need to branch on dimensionality without knowing the input type ahead of time.
Checking if an object has dimensions
# Vectors have NULL dimensions
x <- 1:10
dim(x)
# NULL
# Test with is.null()
is.null(dim(x))
# [1] TRUE
Common patterns
Reshape vectors into matrices: Convert a flat vector into a 2D structure for matrix operations.
Check data frame size: Use dim() to quickly check row and column counts before processing.
Dynamic dimension setting: Create arrays programmatically by assigning dimensions to vectors.
dim() in practice
dim() returns the dimensions of an object or sets them. For a matrix or array, it returns an integer vector: dim(matrix(1:6, 2, 3)) returns c(2, 3). For a data frame, it returns c(nrow, ncol). For a vector, it returns NULL, vectors have no dim attribute, which is why nrow(vector) also returns NULL.
Setting dimensions with dim(x) <- c(r, c) reshapes a vector into a matrix without copying the data: the underlying memory is unchanged, only the dimension attribute is added. This is how matrix() works internally. dim(x) <- c(2, 3, 4) creates a 3D array. Reshaping this way changes how element-access indexing works, since R uses column-major order to map 1D positions to multi-dimensional indices.
dim() is one of R’s key structural attributes alongside names, class, and levels. Removing it with dim(x) <- NULL converts a matrix back to a plain vector, stripping all multi-dimensional interpretation. The elements remain in column-major order in the resulting vector.
For data frames, nrow() and ncol() are more readable than dim()[[1]] and dim()[[2]], but dim() is useful when you need both dimensions at once or when writing generic functions that must handle both matrices and data frames with a single attribute lookup.
dim() returns NULL for 1D vectors and lists. Only matrices, arrays, and data frames carry a dim attribute. Setting dim() on a vector converts it in-place to a matrix: dim(x) <- c(2, 3) reshapes a length-6 vector into a 2x3 matrix, filling column-major (columns before rows).
dim(df) on a data frame returns c(nrow(df), ncol(df)). This is equivalent to c(nrow(df), ncol(df)) but computed in one call. The result is a length-2 integer vector, so dim(df)[1] gives the row count and dim(df)[2] the column count — though nrow() and ncol() are clearer.
For arrays with more than two dimensions, dim() returns a vector of all dimension lengths. dim(arr)[3] gives the size of the third dimension. length(dim(x)) gives the number of dimensions, equivalent to ndim() in Python’s NumPy.
Assigning dim(x) <- NULL strips the dimension attribute from a matrix, converting it back to a plain vector in column-major order.
Working with 3D arrays
dim() handles higher-dimensional arrays naturally, returning a vector with one element per dimension:
# Create a 2 x 3 x 4 array
arr <- array(1:24, dim = c(2, 3, 4))
dim(arr)
# [1] 2 3 4
# Access the size of the third dimension
dim(arr)[3]
# [1] 4
# Number of dimensions (like NumPy ndim)
length(dim(arr))
# [1] 3
# Total number of elements
prod(dim(arr))
# [1] 24
prod(dim(x)) gives the total element count for any array regardless of its dimensionality, including matrices and vectors. This is a safe alternative to length(x) when you want the flat count of individual cells: for a 2×3×4 array, prod(dim(arr)) returns 24, while length(arr) also returns 24 because R stores arrays as flat vectors underneath. The two agree for arrays but diverge for data frames, where length(df) gives the column count rather than the total cell count.
Programmatic dimension checking
Generic functions often need to branch on the dimensionality of their input:
describe_dims <- function(x) {
d <- dim(x)
if (is.null(d)) {
return(paste("1D vector of length", length(x)))
} else if (length(d) == 2) {
return(paste(d[1], "x", d[2], "matrix or data frame"))
} else {
return(paste("Array with", length(d), "dimensions:", paste(d, collapse = " x ")))
}
}
describe_dims(1:10)
# [1] "1D vector of length 10"
describe_dims(matrix(1:6, 2, 3))
# [1] "2 x 3 matrix or data frame"
describe_dims(array(1:24, c(2, 3, 4)))
# [1] "Array with 3 dimensions: 2 x 3 x 4"
This branching pattern based on is.null(dim(x)) and length(dim(x)) is the idiomatic way to write functions that handle vectors, matrices, and arrays polymorphically. It avoids S3 dispatch if you want a single function to behave correctly for multiple input shapes without relying on method registration.