dim() in R: How to Get or Set Dimension of R Objects

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.

Syntax

# To get the dimension value
dim(data)

# To set the dimension value
dim(data) <- value

Parameters

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.

Example

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.

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)[1]
ncol0 <- function(x) dim(x)[2]

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)

Output

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

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

Output

      [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6
[1] 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)

Output

[1] 2 3 4

That is it for dim() function in the R Programming language.

Leave a Comment