Skip to content

Instantly share code, notes, and snippets.

@mathzero
Last active May 4, 2020 19:05
Show Gist options
  • Save mathzero/9461fb2cafcdcbafd5cf098431c313f1 to your computer and use it in GitHub Desktop.
Save mathzero/9461fb2cafcdcbafd5cf098431c313f1 to your computer and use it in GitHub Desktop.
A short function to convert numeric values to scientific notation, eg 0.013 –> 1.3 x 10^-2
### define function for conversion to scientific notation of p-values or other numeric values
scientific_notation <- function (values, digits = 1)
{
if (!is.numeric(values)) {
stop("values must be numbers")
}
if (grepl("^\\d{2}$", digits)) {
stop("digits must a one or two digit whole number")
}
x <- sprintf(paste0("%.", digits, "e"), values)
x <- gsub("e+", " x 10^", x)
x <- ifelse(values == 0, 0, x) # if you are converting pvalues and the value is zero, this keeps it as zero
x
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment