Open In App

Get or Set Dimensions of a Matrix in R Programming – dim() Function

Last Updated : 18 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The dim() function in R is used to get or set the dimensions of an object. This function is particularly useful when working with matrices, arrays, and data frames. Below, we will discuss how to use dim() to both retrieve and set dimensions, with examples for better understanding.

Syntax: dim(x)

Parameters:
x: array, matrix or data frame.

Now we will discuss this with an example in R Programming Language.

R
# R program to illustrate
# dim function

# Getting R Biochemical Oxygen Demand Dataset
BOD 

# Getting dimension of the above dataset
dim(BOD) 

Output:

  Time demand
1 1 8.3
2 2 10.3
3 3 19.0
4 4 16.0
5 5 15.6
6 7 19.8

[1] 6 2

Getting Dimensions of a Matrix

The dim() function returns the dimensions of an object as an integer vector. For a matrix, it returns the number of rows and columns.

R
# Create a matrix
matrix_example <- matrix(1:12, nrow = 3, ncol = 4)

# Print the matrix
print(matrix_example)

# Get the dimensions of the matrix
dimensions <- dim(matrix_example)
print(dimensions)

Output:

       [,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12

[1] 3 4

Conclusion

The dim() function in R is a versatile tool for getting and setting the dimensions of matrices, arrays, and data frames. Whether you need to reshape a vector into a matrix or simply check the size of an existing matrix, dim() provides an easy and efficient way to handle dimensions in R.



Next Article
Article Tags :

Similar Reads