How to Apply the addmargins() Function in R (Example Code)
This article explains how to add margin values on tables or arrays using the addmargins function in R.
Example Data
data(iris) # Example data head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa |
data(iris) # Example data head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa
iris_tab <- table(iris[ , c(1, 5)]) # Cross tabulation iris_tab # Species # Sepal.Length setosa versicolor virginica # 4.3 1 0 0 # 4.4 3 0 0 # 4.5 1 0 0 # 4.6 4 0 0 # 4.7 2 0 0 # 4.8 5 0 0 # 4.9 4 1 1 # 5 8 2 0 # 5.1 8 1 0 # 5.2 3 1 0 # 5.3 1 0 0 # 5.4 5 1 0 # 5.5 2 5 0 # 5.6 0 5 1 # 5.7 2 5 1 # 5.8 1 3 3 # 5.9 0 2 1 # 6 0 4 2 # 6.1 0 4 2 # 6.2 0 2 2 # 6.3 0 3 6 # 6.4 0 2 5 # 6.5 0 1 4 # 6.6 0 2 0 # 6.7 0 3 5 # 6.8 0 1 2 # 6.9 0 1 3 # 7 0 1 0 # 7.1 0 0 1 # 7.2 0 0 3 # 7.3 0 0 1 # 7.4 0 0 1 # 7.6 0 0 1 # 7.7 0 0 4 # 7.9 0 0 1 |
iris_tab <- table(iris[ , c(1, 5)]) # Cross tabulation iris_tab # Species # Sepal.Length setosa versicolor virginica # 4.3 1 0 0 # 4.4 3 0 0 # 4.5 1 0 0 # 4.6 4 0 0 # 4.7 2 0 0 # 4.8 5 0 0 # 4.9 4 1 1 # 5 8 2 0 # 5.1 8 1 0 # 5.2 3 1 0 # 5.3 1 0 0 # 5.4 5 1 0 # 5.5 2 5 0 # 5.6 0 5 1 # 5.7 2 5 1 # 5.8 1 3 3 # 5.9 0 2 1 # 6 0 4 2 # 6.1 0 4 2 # 6.2 0 2 2 # 6.3 0 3 6 # 6.4 0 2 5 # 6.5 0 1 4 # 6.6 0 2 0 # 6.7 0 3 5 # 6.8 0 1 2 # 6.9 0 1 3 # 7 0 1 0 # 7.1 0 0 1 # 7.2 0 0 3 # 7.3 0 0 1 # 7.4 0 0 1 # 7.6 0 0 1 # 7.7 0 0 4 # 7.9 0 0 1
Example: Applying addmargins() Function to Contingency Table
iris_tab_sum <- addmargins(iris_tab, # Put sum to margins FUN = sum) iris_tab_sum # Species # Sepal.Length setosa versicolor virginica sum # 4.3 1 0 0 1 # 4.4 3 0 0 3 # 4.5 1 0 0 1 # 4.6 4 0 0 4 # 4.7 2 0 0 2 # 4.8 5 0 0 5 # 4.9 4 1 1 6 # 5 8 2 0 10 # 5.1 8 1 0 9 # 5.2 3 1 0 4 # 5.3 1 0 0 1 # 5.4 5 1 0 6 # 5.5 2 5 0 7 # 5.6 0 5 1 6 # 5.7 2 5 1 8 # 5.8 1 3 3 7 # 5.9 0 2 1 3 # 6 0 4 2 6 # 6.1 0 4 2 6 # 6.2 0 2 2 4 # 6.3 0 3 6 9 # 6.4 0 2 5 7 # 6.5 0 1 4 5 # 6.6 0 2 0 2 # 6.7 0 3 5 8 # 6.8 0 1 2 3 # 6.9 0 1 3 4 # 7 0 1 0 1 # 7.1 0 0 1 1 # 7.2 0 0 3 3 # 7.3 0 0 1 1 # 7.4 0 0 1 1 # 7.6 0 0 1 1 # 7.7 0 0 4 4 # 7.9 0 0 1 1 # sum 50 50 50 150 |
iris_tab_sum <- addmargins(iris_tab, # Put sum to margins FUN = sum) iris_tab_sum # Species # Sepal.Length setosa versicolor virginica sum # 4.3 1 0 0 1 # 4.4 3 0 0 3 # 4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