What is the addmargins() function in R?

Overview

The addmargins function in R is simply used to add arbitrary margins on a multidimensional table or array.

Syntax

The syntax of the function is as follows:

addmargins(A, margin = seq_along(dim(A)), FUN = sum, quiet = FALSE)

Required parameter value

The addmargins function takes a mandatory parameter value, A, which represents the table or array to which the arbitrary margin is to be added.

Optional parameter value

The addmargins function takes the following optional parameter values:

  • A: This represents the array or table.
  • margin: This is a vector of dimensions over which the margins are to be formed.
  • FUN: This is a list of the same length as the margin parameter, where each element in the list is either a function or a list of functions.
  • quiet: This takes a logical value, which suppresses the message and describes the order in which the margins were computed.

Return value

The addmargins function returns a table or array with the same number of dimensions as the array or table passed to it, but with extra levels of the dimensions given as a value to the margin parameter.

Code example

# creating a matrix object
mymatrix <- matrix (
c( 4, 1, 3,
2, 1, 2,
1, 5, 2,
4, 3, 1),
ncol = 3,
byrow = TRUE
)
# printing the matrix
mymatrix
# calling the addmargins() function
margin_matrix = addmargins(mymatrix, 1, FUN = sum)
# printing the margined matrix
margin_matrix

Code explanation

  • Line 2: We create a matrix object mymatrix that has 3 columns.
  • Line 12: We print the matrix object mymatrix.
  • Line 15: We implement the addmargins() function on the matrix object we created. The result is assigned to a variable margin_matrix.
  • Line 18: We print the variable margin_matrix.

Free Resources