How to Use the dim() Function in R


The dim() function in R can be used to either get or set the dimensions of an array, matrix or data frame.

The following examples show how to use this function in practice.

Example 1: Use dim() to Get Dimensions of Data Frame

Suppose we have the following data frame in R:

#create data frame
df <- data.frame(team=c('A', 'B', 'C', 'D', 'E'),
                 points=c(99, 90, 86, 88, 95),
                 assists=c(33, 28, 31, 39, 34),
                 rebounds=c(30, 28, 24, 24, 28))

#view data frame
df

  team points assists rebounds
1    A     99      33       30
2    B     90      28       28
3    C     86      31       24
4    D     88      39       24
5    E     95      34       28

We can use the dim() function to retrieve the number of rows and columns in the data frame:

#get dimensions of data frame
dim(df)

[1] 5 4

From the output we can see that the data frame has 5 rows and 4 columns.

Example 2: Use dim() to Get Dimensions of Matrix

Suppose we have the following matrix in R:

#create matrix
mat <- matrix(c(1, 4, 4, 8, 5, 4, 3, 8), nrow=4)

#view matrix
mat

     [,1] [,2]
[1,]    1    5
[2,]    4    4
[3,]    4    3
[4,]    8    8

We can use the dim() function to retrieve the number of rows and columns in the matrix:

#get dimensions of matrix
dim(mat)

[1] 4 2

From the output we can see that the matrix has 4 rows and 2 columns.

Example 3: Use dim() to Set Dimensions of Matrix

We can also use dim() to set the dimensions of a matrix:

#create vector of values
x <- c(1, 4, 4, 8, 5, 4, 3, 8)

#define dimensions for values 
dim(x) <- c(4, 2)

#view result
x

     [,1] [,2]
[1,]    1    5
[2,]    4    4
[3,]    4    3
[4,]    8    8

#view class
class(x)

[1] "matrix" "array" 

The result is a matrix (and an array) with 4 rows and 2 columns.

Example 4: Use dim() to Get One Dimension

We can also use dim(x)[1] and dim(x)[2] to retrieve just the number of rows or just the number of columns of an object.

For example, suppose we have the following matrix:

#create matrix
x <- matrix(c(1, 4, 4, 8, 5, 4, 3, 8), nrow=4)

#view matrix
x

     [,1] [,2]
[1,]    1    5
[2,]    4    4
[3,]    4    3
[4,]    8    8

We can use dim(x)[1] to only get the number of rows:

#display number of rows in matrix
dim(x)[1]

[1] 4

And we can use dim(x)[2] to only get the number of columns:

#display number of columns in matrix
dim(x)[2]

[1] 2

Additional Resources

The following tutorials explain how to use other common functions in R:

How to Use tabulate() Function in R
How to Use length() Function in R
How to Use replicate() Function in R

Leave a Reply

Your email address will not be published.