The as.table() function in R is used to convert a matrix object to an object of class table.
Let’s view the syntax:
as.table(x)
The as.table() function takes a single and mandatory parameter, x, which represents the matrix object.
The as.table() function returns an object of class table.
Let’s look at an example below:
# using the matrix() function to create a matrixmymatrix <- matrix(c("Theo","Chidalu","David","Marshal","Sammy","Pedro"), #datanrow = 2, # number of rowsncol = 2, # number of columnsbyrow = FALSE, # matrix fillingdimname = list(c("row1", "row2"),c("Col1", "Col2")) # names of rows and columns)# implementing the as.table() functionmytable = as.table(mymatrix)mytable# checking the object classesclass(mymatrix)class(mytable)
Lines 1 to 11: We create a matrix, mymatrix, in which we use the matrix() function and its various parameter values to make the mymatrix become a 2 × 2 matrix (2 rows and 2 columns matrix) and also with their dimension names (row1, row2, col1, and col2).
Line 14: We implement the as.table() function on the matrix mymatrix. The result is assigned to a variable mytable.
Line 15: We print the variable mytable.
Line 18: We use the class() function to obtain and print the object class of the variable mymatrix.
Line 19: We use the class() function to obtain and print the object class of the variable mytable.