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

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

by Erma Khan
spot_img

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

my_matrix 

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 frame(team=c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'),
                 position=c('G', 'G', 'F', 'C', 'G', 'F', 'C', 'C'))

#view data frame
df

  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 #view table
my_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
class(my_table)

[1] "table"

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

#convert table to matrix
my_matrix #view matrix
my_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
class(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

spot_img

Related Posts