What is the margin.table() function in R?

Overview

In R, the margin.table() function is used to compute the sum of table entries for a given index ( 1 for rows and 2 for columns).

Syntax

The syntax of the function is given below:

margin.table(x, margin = NULL)
Syntax for the margin.table() funciton in R

Parameters

The margin.table() function takes the following parameter values:

  • x : This is the input array. It is a required parameter.

  • margin : This is the index number representing either the row (1) or the column (2). It is a required parameter.

Return value

The margin.table() function returns a relevant marginal table of the summed rows or summed columns.

Example

Let's look at an example use case of the margin.table() function:

# creating an array object
myarray <- matrix (
c( 4, 1, 3,
2, 1, 2,
1, 5, 2,
4, 3, 1),
ncol = 3,
byrow = TRUE
)
# getting the sum of each of the rows
margin.table(myarray, 1)
# getting the sum of each of the columns
margin.table(myarray, 2)

Explanation

  • Line 2: We create an array object (matrix), myarray, with 4 rows and 3 columns, using the matrix() function.

  • Line 12: We obtain and print the values for the sum of each row of the matrix using the margin.table() function with the index number of 1.

  • Line 15: We obtain and print the values for the sum of each column of the matrix using the margin.table() function with the index number of 2.

Free Resources