# The dim() Function In R: How To Use The Dim Function in R

In this tutorial, you will learn how to use the dim() function in R. The dim() function in R can help you get and set the dimension of the array, matrix, or data frame. Let’s follow this article to learn more about it with the explanation and examples below.

## Dim Function In R

What does dim() do in R?

The dim() function in R can help you get the dimension of an array, the matrix, or the data frame if you take the R object as a parameter. Besides that, you can also set the dimension of an object if you assign the value to the dim() function.

Syntax:

To get the dimension of an object, use it.

dim(data)

To set the dimension of an object, use it.

dim(data) <- value

Parameters:

• data: The R object: an array, a matrix or a data frame.
• value: The vector that is the new dimension of the object.

After learning the usage and syntax of the dim() function, you will learn how to use it in the next title below.

## How to use the Dim function in R?

You can use the dim() function to get or set the dimension of the objects: an array, a vector or a data frame.

### Get the dimension of an object

You can get the dimension of the objects by the dim() function.

Look at the example below to learn how to use it.

df <- data.frame(
Name = c("Peter","Helen","John","Mendy","Zaha"),
Salary =c(1000, 2000, 4323, 2112, 5000),
Bonus = c(20, 40, 60, 80, 100)
)

# Get the dimension of the data frame by dim() function
dim(df)

Output

[1] 5 3

By the same way, you can get the dimension of an array or a matrix. But note that you can not get the dimension of the vector by this method. It always returns NULL.

Look at the example below.

data <- c(1, 2, 3, 4, 5 ,6 ,7, 8, 9)

# Get the dimension of the vector
dim(data)

Output

NULL

### Set the dimension of an object

You can also set the dimension of an object by the dim() function.

Look at the example below.

data <- c(1, 2, 3, 4, 5 ,6 ,7, 8, 9, 10)

# Convert the current data to a matrix that has two rows and five columns
dim(data) <- c(2,5)

data

Output

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

## Summary

You have learned about the usage, syntax, and how to use the dim() function in R. By this function, you can get and set the dimension of the array, matrix, or data frame. If you have any questions about this tutorial, leave a comment below. I will answer your questions. Thanks!

Maybe you are interested:

Posted in R