How to put margins on tables or arrays in R?, I’ll show you how to use the addmargins function in the R programming language to add margins to tables or arrays in this post.
The addmargins function will be used in the tutorial’s two examples to annotate the margin values on table objects.
To be more specific, the instruction includes the following details:
Providing Examples of Data
The data listed below will serve as the foundation for this R tutorial.
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
Consider the previous table. It demonstrates how the sample data frame has two variables and six rows.
Then, using these data, we can build a table object (a contingency table).
tab <- table(data) tab
x2 x1 a b A 1 0 B 1 2 C 1 1
Example 1:-Incorporate Sum Margins into the Contingency Table.
Addmargins() Function Utilization
I’ll show you how to add the sum of each row and column to a table’s margins using the addmargins function in Example 1.
Take into account 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 a row and column that contain the sum margins of our data that are annotated.
Hope you enjoyed it.