dim

Basics

dim is a function that allows us to return or set the dimension of an object. We read the output/input of dim as [rows, columns].


Examples

How do I get the dimensions of a dataset?

Click to see solution
# R built-in: 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 an object?

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

As we can see, x is a one-dimensional vector with 9 values, which we can say is 1 row and 9 columns. Let’s make x a matrix with 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

As we can see from this example, R fills the columns before the rows when changing a vector to a matrix.