The dim has a method for data frames, which returns the length of the row.names attribute of input data, and the length of input data is the numbers of “rows” and “columns”.
dim() in R
The dim() is an inbuilt R function that either sets or returns the dimension of the matrix, array, or data frame. The dim() function takes the R object as an argument and returns its dimension, or if you assign the value to the dim() function, then it sets the dimension for that R Object.
# To get the dimension value dim(data) # To set the dimension value dim(data) <- value
The data is an input R Object whose dimension we have to get.
If we want to assign a new dimension, then use the second syntax.
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)
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:  4 5
From the output, you can see that our data frame has (4, 5) dimensions. We have four rows and five columns.
For the data frame, the `dim()` function returns the number of rows and columns as an integer vector.
The functions dim() and dim<- are generic.
The simple versions of nrow and ncol could be defined as follows.
nrow0 <- function(x) dim(x) ncol0 <- function(x) dim(x)
Find the dimension of Vector in R
To find the dimension of the Vector, use the dim() function. The dimension of the vector always returns NULL.
rv <- c("u", "v", "w", "x") cat("The dimension of Vector is: ", "\n") dim(rv)
The dimension of Vector is: NULL
And it returns NULL. The dimension of the Vector in R is NULL.
To get the number of elements of the Vector, use the length() function.
Set dimension of a matrix in R
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
 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 dimension to multi-dimensions using the dim() function.
How to find the dimension of Matrix in R
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)
[,1] [,2] [1,] 1 4 [2,] 2 5 [3,] 3 6  3 2
dim() of Array in R
To get the dimension of the array in R, use the dim() function.
arr <- array(1:24, dim = 2:4) dim(arr)
 2 3 4
That is it for dim() function in the R Programming language.
Krunal Lathiya is an Information Technology Engineer by education and web developer by profession. He has worked with many back-end platforms, including Node.js, PHP, and Python. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language. Krunal has written many programming blogs, which showcases his vast expertise in this field.