To add a column sums row at the bottom of the cross table, rbind
the result above with colSums
. Note that there's no longer need for print(tbl, na.print = NA)
, the method print
(autoprint) being called is now the matrix method.
library(data.table)toy_data = data.table(from=c("A","A","A","C","E","E","A","A","A","C","E","E"),to=c("B","C","A","D","F","E","E","A","A","A","C",NA))levels <- sort(unique(unlist(toy_data)))levels <- levels[!is.na(levels)]toy_data[, c("from", "to") := lapply(.SD, factor, levels = levels)]tbl <- table(toy_data)class(tbl) # check the output object class#> [1] "table"tbl <- rbind(tbl, tot = colSums(tbl, na.rm = TRUE))is.na(tbl) <- tbl == 0class(tbl) # check the output object class, it's no longer "table"#> [1] "matrix" "array"tbl#> A B C D E F#> A 3 1 1 NA 1 NA#> B NA NA NA NA NA NA#> C 1 NA NA 1 NA NA#> D NA NA NA NA NA NA#> E NA NA 1 NA 1 1#> F NA NA NA NA NA NA#> tot 4 1 2 1 2 1
Created on 2022-03-29 by the reprex package (v2.0.1)