Even later:
As pointed out by @DzimitryM, percent()
has been "retired" in favor of label_percent()
, which is a synonym for the old percent_format()
function.
label_percent()
returns a function, so to use it, you need an extra pair of parentheses.
library(scales)
x <- c(-1, 0, 0.1, 0.555555, 1, 100)
label_percent()(x)
## [1] "-100%" "0%" "10%" "56%" "100%" "10 000%"
Customize this by adding arguments inside the first set of parentheses.
label_percent(big.mark = ",", suffix = " percent")(x)
## [1] "-100 percent" "0 percent" "10 percent"
## [4] "56 percent" "100 percent" "10,000 percent"
An update, several years later:
These days there is a percent
function in the scales
package, as documented in krlmlr's answer. Use that instead of my hand-rolled solution.
Try something like
percent <- function(x, digits = 2, format = "f", ...) {
paste0(formatC(100 * x, format = format, digits = digits, ...), "%")
}
With usage, e.g.,
x <- c(-1, 0, 0.1, 0.555555, 1, 100)
percent(x)
(If you prefer, change the format from "f"
to "g"
.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…