Adding Rows To a Contingency Table

Solution 1:

You can do that by rbind(your_ftable, total = ...). This will create a row with the name total after the last row of your_ftable. For instance,

summary <- xtabs(~dates+name+types+types2, problem_data)
t <- ftable(summary, row.vars=1, col.vars=2:4)
totals <- problem_data %>% group_by(name,  types, types2) %>% summarise(totals = n())
memisc::show_html(rbind(t, totals = totals$totals), varinfront = FALSE)

gives

result

Further reading: https://cran.r-project.org/web/packages/memisc/vignettes/ftable-matrix.html

Solution 2:

Using the group_by needs one to figure out the ordeing in which the variables occur. instead, I Would prefer to use the addmargins function. Which adds the margins to the data. The only trick is to change the attributes:

v <- attributes(t)
result <- addmargins(t, 1) #Adds the totals
v$row.vars[[1]] <- c(v$row.vars[[1]], 'Total')
v$dim <- dim(result)
attributes(result) <- v
memisc::show_html(result)

enter image description here