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
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
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
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.