Skip to content

Instantly share code, notes, and snippets.

@shv38339
Last active April 18, 2017 20:33
Show Gist options
  • Save shv38339/95e6123cd9c8f60c3f83637b90ea8b9b to your computer and use it in GitHub Desktop.
Save shv38339/95e6123cd9c8f60c3f83637b90ea8b9b to your computer and use it in GitHub Desktop.
Code snippet displays a customized HTML table function and an example. My next step is to copy and paste this HTML table into an excel file, which I then copy and paste into a word document.
# Quite a few requirements so read closely
# - variable must filter out NAs
# - variable must be a factor
# - variable must have factor labels (i think)
# - must be slightly comfortable with dplyr
# FUNCTION
tbl_steele <- function(data, names){
require(htmlTable)
a <- lapply(data, function(x) freq(x, plot = F))
b <- do.call(rbind, a)
remove_total <- "Total"
d <- b[!rownames(b) %in% remove_total, ]
e <- data.frame(d)
e_prettyNum <- prettyNum(e$Frequency, big.mark = ",", scientific = FALSE, preserve.width = "none")
f <- cbind(paste(e_prettyNum, " ", "(", round(e$Percent, 1), ")", sep = ""))
g <- lapply(data, function(x) length(levels(x)))
g1 <- do.call(rbind, g)
h <- htmlTable(f, rnames = rownames(d), rgroup = names, n.rgroup = c(g1))
return(h)
}
# EXAMPLE
# requires dplyr as I use the filter function to filter out NAs as function will not properly run
# Again, filter out NAs before passing varaible through function
mtcars %>%
select(gear) %>%
transmute(gear_fctr = factor(gear,
levels = c(3, 4, 5),
labels = c("3. Three", "4. Four", "5. Five"))) %>%
tbl_steele(data = ., names = names(.))
# COUNTER EXAMPLE TO "UNFACTORED" VARIABLE
# Change transmute to mutate and you'll see the weird behavior
mtcars %>%
select(gear) %>%
mutate(gear_fctr = factor(gear,
levels = c(3, 4, 5),
labels = c("3. Three", "4. Four", "5. Five"))) %>%
tbl_steele(data = ., names = names(.))
# function is in its infancy, hence the strict requirements (sorry)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment