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).
The syntax of the function is given below:
margin.table(x, margin = NULL)
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.
The margin.table()
function returns a relevant marginal table of the summed rows or summed columns.
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)
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
.