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)
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 objectmyarray <- 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 rowsmargin.table(myarray, 1)# getting the sum of each of the columnsmargin.table(myarray, 2)
Explanation
Line 2: We create an array object (matrix),
myarray, with4rows and3columns, using thematrix()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 of1.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 of2.