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

dim() Function in detail

The dim() function in R is used to obtain or modify the dimensions of an object. This function is particularly helpful when working with matrices, arrays, and data frames. Below, we explore how to use dim() to both retrieve and set dimensions, along with practical examples for clarity.

Syntax:

dim(x)

Parameters:

  • x: An array, matrix, or data frame.
dim(x)
Retrieving Dimensions of a Data Frame

The dim() function returns the number of rows and columns in a data frame.

Example: Getting Dimensions of a Built-in Dataset

R provides built-in datasets that can be used to demonstrate the function. Here, we use the mtcars dataset.

# Display the first few rows of the dataset
head(mtcars)

# Get the dimensions of the dataset
dim(mtcars)

Output:

mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6  160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6  160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4  108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6  258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8  360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6  225.0 105 2.76 3.460 20.22  1  0    3    1

[1] 32 11
Retrieving Dimensions of a Matrix

For matrices, dim() returns the number of rows and columns as an integer vector.

Example: Using dim() with a Matrix

# Creating a matrix with 4 rows and 3 columns
my_matrix <- matrix(1:12, nrow = 4, ncol = 3)

# Display the matrix
print(my_matrix)

# Retrieve dimensions of the matrix
matrix_dimensions <- dim(my_matrix)
print(matrix_dimensions)

Output:

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

[1] 4 3

Here, dim() returns [1] 4 3, indicating the matrix has 4 rows and 3 columns.

Setting Dimensions of a Vector

The dim() function can also be used to assign dimensions to a vector, effectively transforming it into a matrix.

Example: Assigning Dimensions to a Vector

# Creating a vector with 9 elements
my_vector <- 1:9

# Setting dimensions to convert the vector into a matrix (3 rows, 3 columns)
dim(my_vector) <- c(3, 3)

# Display the transformed matrix
print(my_vector)

# Retrieve its new dimensions
print(dim(my_vector))

Output:

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

[1] 3 3

By setting dim(my_vector) <- c(3, 3), the vector is converted into a 3×3 matrix.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *