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 matrix
mymatrix <- matrix(
c("Theo","Chidalu","David","Marshal","Sammy","Pedro"), #data
nrow = 2, # number of rows
ncol = 2, # number of columns
byrow = FALSE, # matrix filling
dimname = list(
c("row1", "row2"),
c("Col1", "Col2")
) # names of rows and columns
)
# implementing the as.table() function
mytable = as.table(mymatrix)
mytable
# checking the object classes
class(mymatrix)
class(mytable)

Explanation

  • 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.

Free Resources