How to Convert a Table to a Matrix in R (With Example)

You can use the following basic syntax to convert a table to a matrix in R:

my_matrix <- matrix(my_table, ncol=ncol(my_table), dimnames=dimnames(my_table))

The following example shows how to use this syntax in practice.

Example: Convert Table to Matrix in R

First, let’s create the following data frame in R that shows the team and position of various basketball players:

#create data frame
df <- data.frame(team=c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'),
                 position=c('G', 'G', 'F', 'C', 'G', 'F', 'C', 'C'))

#view data frame

  team position
1    A        G
2    A        G
3    A        F
4    A        C
5    B        G
6    B        F
7    B        C
8    B        C

Next, let’s create a table that displays the frequency of each combination of team and position:

#create frequency table of values for team and position
my_table <- table(df$team, df$position)

#view table

    C F G
  A 1 1 2
  B 2 1 1

We can use the class() function to confirm that the object called my_table is indeed a table:

#display class of my_table

[1] "table"

Next, we can use the following syntax to convert the table to a matrix:

#convert table to matrix
my_matrix <- matrix(my_table, ncol=ncol(my_table), dimnames=dimnames(my_table))

#view matrix

    C F G
  A 1 1 2
  B 2 1 1

And we can use the class() function to confirm that the object called my_matrix is indeed a matrix:

#display class of my_matrix

[1] "matrix" "array"

Note #1: The ncol argument ensures that the number of columns in the matrix match the number of columns in the table.

Note #2: The dimnames argument ensures that the row names and column names match the ones from the table.

Additional Resources

The following tutorials explain how to perform other common operations in R:

How to Convert Table to Data Frame in R
How to Convert Matrix to Vector in R
How to Convert List to Matrix in R
How to Convert Data Frame Column to Vector in R

Leave a Reply

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