Skip to content

Instantly share code, notes, and snippets.

@tjmahr
Last active August 29, 2015 14:16
Show Gist options
  • Save tjmahr/23ef6fc655a1e6bc526f to your computer and use it in GitHub Desktop.
Save tjmahr/23ef6fc655a1e6bc526f to your computer and use it in GitHub Desktop.
pretty printing
# Code for formatting numbers (for my knitr docs)
library("magrittr")
library("dplyr", warn.conflicts = FALSE)
library("broom")
library("stringr")
# Fixed width integers (like for track or image numbers in filenames)
sprintf("%03.f", seq_len(20))
# [1] "001" "002" "003" "004" "005" "006" "007" "008" "009" "010"
#[11] "011" "012" "013" "014" "015" "016" "017" "018" "019" "020"
# p-values
model <- lm(Sepal.Length ~ Species * Sepal.Width, iris) %>% tidy %T>% print
# term estimate std.error statistic p.value
# 1 (Intercept) 2.6390012 0.5715053 4.6176320 8.526118e-06
# 2 Speciesversicolor 0.9007335 0.7987512 1.1276772 2.613317e-01
# 3 Speciesvirginica 1.2678352 0.8161509 1.5534324 1.225149e-01
# 4 Sepal.Width 0.6904897 0.1657268 4.1664328 5.311035e-05
# 5 Speciesversicolor:Sepal.Width 0.1745880 0.2598919 0.6717717 5.028054e-01
# 6 Speciesvirginica:Sepal.Width 0.2110448 0.2557557 0.8251811 4.106337e-01
# Print two digits of a p-value, but use the "< .001" notation on tiny values.
format_pval <- function(ps, html = FALSE) {
template <- ifelse(html, "&lt;&nbsp;.001", "< .001")
ps_chr <- ps %>%
get_digits(2) %>%
remove_leading_zero
ps_chr[ps < 0.001] <- template
ps_chr
}
# Get n significant digits
get_digits <- function(xs, n = 2) {
formatC(xs, digits = n, format = "fg")
}
# Don't need a leading zero on bounded numbers like p-values
remove_leading_zero <- function(xs) {
str_replace(xs, "^0", "")
}
model %>%
mutate(p = format_pval(p.value)) %>%
mutate_each(funs(round(., 2)), estimate:p.value)
# term estimate std.error statistic p.value p
# 1 (Intercept) 2.64 0.57 4.62 0.00 < .001
# 2 Speciesversicolor 0.90 0.80 1.13 0.26 .26
# 3 Speciesvirginica 1.27 0.82 1.55 0.12 .12
# 4 Sepal.Width 0.69 0.17 4.17 0.00 < .001
# 5 Speciesversicolor:Sepal.Width 0.17 0.26 0.67 0.50 .5
# 6 Speciesvirginica:Sepal.Width 0.21 0.26 0.83 0.41 .41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment