What is the as.table() function in R?
Overview
The as.table() function in R is used to convert a matrix object to an object of class table.
Syntax
Let’s view the syntax:
as.table(x)
Parameter
The as.table() function takes a single and mandatory parameter, x, which represents the matrix object.
Return value
The as.table() function returns an object of class table.
Example
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)
Explanation
-
Lines 1 to 11: We create a matrix,
mymatrix, in which we use thematrix()function and its various parameter values to make themymatrixbecome a2 × 2matrix (2 rows and 2 columns matrix) and also with their dimension names (row1,row2,col1, andcol2). -
Line 14: We implement the
as.table()function on the matrixmymatrix. The result is assigned to a variablemytable. -
Line 15: We print the variable
mytable. -
Line 18: We use the
class()function to obtain and print the object class of the variablemymatrix. -
Line 19: We use the
class()function to obtain and print the object class of the variablemytable.