How to Put margins on tables or arrays in R
How to Put margins on tables or arrays in R, We’ll show you how to use the addmargins function in R to add margins to tables or arrays.
The tutorial will include two examples of using the addmargins function to annotate margin values on table objects.
Let’s get this party started:
How to Put margins on tables or arrays in R
For this R tutorial, we’ll start with the data below:
data <- data.frame(x1 = c(LETTERS[1:3],      "B", "B", "C") x2 = letters[1:2]) data                                        Â
x1 x2 1Â AÂ a 2Â BÂ b 3Â CÂ a 4Â BÂ b 5Â BÂ a 6Â CÂ b
Examine the preceding table. It shows that the example data frame has six rows and two variables.
Best Data Science Algorithms » finnstats
Based on these data, we can then create a table object (i.e. a contingency table).
tab <- table(data)                        tab                                      Â
x2 x1 a b  A 1 0  B 1 2  C 1 1
The preceding RStudio console output shows our table without margins.
Example 1: Assign Sum Margins to a Contingency Table Using the function addmargins()
Example 1, Will show how to use the addmargins function to add the sum of each row and column to a table’s margins.
Consider the R code below:
tab_sum <- addmargins(tab, FUN = sum)     tab_sum                                     Â
x2 x1   a b sum  A  1 0  1  B  1 2  3  C  1 1  2  sum 3 3  6
As you can see, we have annotated another row and column with our data’s sum margins.
Data Science applications in Retail » finnstats
Example 2: Assign Mean Margins to a Contingency Table Using the function addmargins()
We used the sum function in Example 1 to add margins to our contingency table.
However, other functions within the addmargins command can be used.
The R code below demonstrates how to annotate mean values to a table object:
tab_mean <- addmargins(tab, FUN = mean)   tab_mean                                   Â
x2 x1      a  b mean  A   1.0 0.0 0.5  B   1.0 2.0 1.5  C   1.0 1.0 1.0  mean 1.0 1.0 1.0
The previous table has the same structure as Example 1. However, instead of sum margins, we have included mean margins this time.