Created
March 21, 2013 23:04
-
-
Save kbroman/5217617 to your computer and use it in GitHub Desktop.
R function to deal with sprintf("%.2f", ...) returning -0.00
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# a function to deal with sprintf("%.2f", ...) returning -0.00 | |
# see https://twitter.com/hspter/status/314858331598626816 | |
f <- function(..., dig=2) { | |
g <- sprintf(paste0("%.", dig, "f"), ...) | |
z <- paste0("0.", paste(rep("0", dig), collapse="")) | |
g[g==paste0("-",z)] <- z | |
g | |
} | |
# this should return c("0.000", "0.000", "0.500", "-0.500", "-0.002") | |
f(c(-0.0002, 0.0002, 0.5, -0.5, -0.002), dig=3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This worked like a charm. Thank you!