Skip to content

Instantly share code, notes, and snippets.

@arnauldvm
Last active March 13, 2019 15:36
Show Gist options
  • Save arnauldvm/1650ad518509598ce88258c06d1f8fa1 to your computer and use it in GitHub Desktop.
Save arnauldvm/1650ad518509598ce88258c06d1f8fa1 to your computer and use it in GitHub Desktop.
R engineering notation
si_prefixes_positive = c("k", "M", "G", "T", "P", "E", "Z", "Y")
si_prefixes_negative = c("m", "µ", "n", "p", "f", "a", "z", "y")
engineering_notation = function(x, digits=6, digitsafter=NA, si_prefix=TRUE, scale=1, unit="") {
if (is.na(x)) return(NA)
negative = (x<0)
x = scale*abs(x)
if (x==0) {
# ! log10(0) = -Inf
pow = 0
digitsbefore = 1
} else {
dim = floor(log10(x))
pow = 3 * dim %/% 3
digitsbefore = 1+dim%%3
}
if (is.na(digitsafter)) digitsafter = digits - digitsbefore
if (digitsafter<0) digitsafter=0
if (pow==0) format = sprintf("%%%d.%df", digitsbefore, digitsafter) # e.g. %3.2f
else if (!si_prefix) format = sprintf("%%%d.%dfE%%d", digitsbefore, digitsafter) # e.g. %3.2fE%d
else format = sprintf("%%%d.%df%%s", digitsbefore, digitsafter) # e.g. %3.2f%s
if (negative) format = paste0("-", format)
mantissa = signif(x/(10^pow), digitsbefore+digitsafter)
if (pow==0) res = sprintf(format, mantissa)
else if (!si_prefix) res = sprintf(format, mantissa, pow)
else {
if (pow>0) pref = si_prefixes_positive[pow%/%3]
else pref = si_prefixes_negative[(-pow)%/%3]
res = sprintf(format, mantissa, pref)
}
return(paste0(res, unit))
}
engineering_notation_labels = function(breaks, digits=3, digitsafter=0, si_prefix=TRUE, scale=1, unit="") {
return(sapply(breaks, FUN=function(x) engineering_notation(x=x, digits=digits, digitsafter=digitsafter, si_prefix=si_prefix, scale=scale, unit=unit)))
}
# Usage:
FORMAT_SIZE_IN_B = function(x) engineering_notation_labels(x, scale=1, unit="b")
ggplot(...) + ... + scale_x_log10(labels=FORMAT_SIZE_IN_B)
ms_to_durationstring = function(ms) {
return(engineering_notation(ms, digits=4, scale=0.001, unit="s"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment