Skip to content

Instantly share code, notes, and snippets.

@jennybc
Last active August 29, 2015 14:01
Show Gist options
  • Save jennybc/1f1853f9ee30f2d76930 to your computer and use it in GitHub Desktop.
Save jennybc/1f1853f9ee30f2d76930 to your computer and use it in GitHub Desktop.
Get multi-factor tabulation into a data.frame AND append a row for a grand total
library(plyr)
## what's the best way to get tabulation of (days31, oystersOK) into a
## data.frame AND get a grand total row reflecting the expected total of 12
## months?
## related discussion has occured before here:
## http://stackoverflow.com/questions/4946873/how-do-i-add-a-row-to-a-data-frame-with-totals
## related issue open on dplyr:
## https://github.com/hadley/dplyr/issues/435
## my use case has some different elements, so I'll add it to the mix
inDat <- c("month days31 oystersOK",
"January TRUE TRUE",
"February FALSE TRUE",
"March TRUE TRUE",
"April FALSE TRUE",
"May TRUE FALSE",
"June FALSE FALSE",
"July TRUE FALSE",
"August TRUE FALSE",
"September FALSE TRUE",
"October TRUE TRUE",
"November FALSE TRUE",
"December TRUE TRUE")
inDat <- read.table(text = inDat, header = TRUE, stringsAsFactors = FALSE)
## the tabulation I want
outDat <- count(inDat, c("days31", "oystersOK"))
## two kludgy ways to add the grand total row, prior to use of, e.g. kable()
join(outDat, data.frame(freq = sum(outDat$freq)), type = "full")
rbind(outDat, c("--", "--", sum(outDat$freq)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment