Reputation: 317
I have for example a vector like that:
time <- c(0, 0.5, 1, 1.5, 2, 2.5)
If I have to write the third element in a graph I have to use this command:
text(7.5,75, time[3])
It appears as a 1, but I want it as 1.0, how can I make the first decimal digits appear?
Upvotes: 1
Views: 890
Reputation: 109874
Here's one approach that wraps sprintf
. It's one I keep around for reports. Note it also removes non significant leading zeros.
numfor <- function (val, digits, override = FALSE) {
if (all(is.Integer(val), na.rm = TRUE) & !override) {
sub("^(-?)0.", "\\1.", sprintf(paste0("%.0f"), val))
} else {
sub("^(-?)0.", "\\1.", sprintf(paste0("%.", digits, "f"), val))
}
}
is.Integer <- function(x, tol = .Machine$double.eps^0.5) {
abs(x - round(x)) < tol
}
time <- c(0, 0.5, 1, 1.5, 2, 2.5)
numfor(time, 1)
## [1] ".0" ".5" "1.0" "1.5" "2.0" "2.5"
And what override
does:
## > numfor(1:10, 1)
## [1] "1" "2" "3" "4" "5" "6" "7" "8" "9" "10"
## > numfor(1:10, 1, override=TRUE)
## [1] "1.0" "2.0" "3.0" "4.0" "5.0" "6.0" "7.0" "8.0" "9.0" "10.0"
Upvotes: 2