dim

dim is a function that allows us to return or set the dimension of a matrix, array or data frame.

Examples

How do I get the dimensions of a dataset?

Click to see solution
# Getting R Biochemical Oxygen Demand Dataset
BOD

# Getting dimension of the above dataset
dim(BOD)
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

How do I change the dimensions of a variable?

Click to see solution
#Let's set x to include every number from 1 to 9.
x <- rep(1:9)
x
[1] 1 2 3 4 5 6 7 8 9

As we can see, X is currently 1 row and 9 columns. Let’s resize this to have 3 rows and 3 columns.

dim(x) <- c(3, 3)
x
      [, 1] [, 2] [, 3]
[1, ]    1    4    7
[2, ]    2    5    8
[3, ]    3    6    9