The dim() function in R is “used to get or set the dimensions of a matrix, array, or data frame“. For example, dim(m) returns the dimensions of m, and dim(m) <- c(3, 4) sets the dimensions for m, which has 3 rows and 4 columns.
Syntax
# To get the dimension value
dim(data)
# To set the dimension value
dim(data) <- value
Parameters
data: It is an input R Object whose dimension we must get.
Return value
The dim() function returns NULL for a vector or a numeric vector for a data frame, matrix, or array.
Example 1:Use the dim() function to get the dimensions of the Data Frame
df <- data.frame(c1 = c("a", "b", "c", "d"),
c2 = c("e", "f", "g", "h"),
c3 = c("i", "j", "k", "l"),
c4 = c("m", "n", "o", "p"),
c5 = c("q", "r", "s", "t"))
df
cat("The dimension of data frame is: ", "\n")
dim(df)
Output
c1 c2 c3 c4 c5
1 a e i m q
2 b f j n r
3 c g k o s
4 d h l p t
The dimension of data frame is:
[1] 4 5
From the output, you can see that our data frame has (4, 5) dimensions. We have four rows and five columns.
The ‘dim()’ function returns the number of rows and columns as an integer vector for the data frame.
The functions dim() and dim<- are generic.
The simple versions of nrow and ncol could be defined as follows.
nrow0 <- function(x) dim(x)[1]
ncol0 <- function(x) dim(x)[2]
Example 2: Use dim() to set dimensions of Matrix
To set the dimension of the matrix, define a vector and use the dim() function to set the dimension.
rv <- rep(1:10)
rv
dim(rv) <- c(2, 5)
rv
Output
[1] 1 2 3 4 5 6 7 8 9 10
[,1] [,2] [,3] [,4] [,5]
[1,] 1 3 5 7 9
[2,] 2 4 6 8 10
We change the dimension from one to multi-dimensions using the dim() function.
Example 3: Use dim() function to get dimensions of Matrix
To get the dimension of the matrix in R, use the dim attribute of the object.
rv <- 1:6
mtrx <- matrix(rv, 3, 2)
mtrx
dim(mtrx)
Output
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
[1] 3 2
Example 4: Use the dim() function to get the dimensions of the array
To get the dimension of the array in R, use the dim() function.
arr <- array(1:24, dim = 2:4)
dim(arr)
Output
[1] 2 3 4
Example 5: Use the dim() function to get the dimensions of the list
If you try to use dim() on a list, you’ll likely get “NULL” because a list in R is not inherently multi-dimensional like a matrix or array.
list1 <- list(c(19, 21, 18), c(46, 50, 60))
dim(list1)
Output
NULL
Example 6: Use the dim() function to get the dimensions of the vector
A vector is a one-dimensional object and, thus, doesn’t have dimensions in the way that a matrix or array does. That’s why if you pass the vector to the dim() function, it returns NULL.
rv <- c(19, 21, 18)
dim(rv)
Output
NULL
That’s it.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language.