R语言 把数字格式化为百分比
在这篇文章中,我们将看到如何在R编程语言中把数字格式化为百分比。
方法1:使用formattable包
formattable “包提供了创建formattable向量和数据框对象的方法。R语言中的这个包可以安装,并使用命令.NET加载到工作空间。
install.packages("formattable")
本软件包中的 percent() 方法用于以百分比格式表示数字向量。
语法: percent(vec, digits, format = “f”, …)
参数 :
- vec – 要转换为百分比格式的向量
- digits – 小数点后的数字。默认情况下,位数相当于2。
- format – 传递给format方法的格式类型字符串。
代码
# loading the required libraries
library("formattable")
# creating a vector
vec <- c(0.76485, 1.34, -0.6, 1)
print ("Percentage conversion : 2 digits")
percent (vec)
print ("Percentage conversion : 4 digits")
percent (vec, 4)
输出
[1] "Percentage conversion : 2 digits"
[1] "76.48%" "134.00%" "-60.00%" "100.00%"
[1] "Percentage conversion : 4 digits"
[1] "76.4850%" "134.0000%" "-60.0000%" "100.0000%"
方法2:使用scales包
R语言中的 “scales “包可以通过以下命令安装并加载到工作空间。
install.packages("scales")
本软件包中的 percent() 方法用于将数字向量表示为百分比格式。
语法: percent(vec)
参数: vec – 要转换为百分比格式的向量
代码
# loading the required libraries
library("scales")
# creating a vector
vec <- c(0.76485, 1.34, -0.6, 1)
print ("Percentage conversion")
percent (vec)
输出
[1] "Percentage conversion"
[1] "76%" "134%" "-60%" "100%"
方法3:使用用户定义的函数
一个用户定义的方法可以用来将一个数字转换成百分比格式。这个函数中使用的格式指定符是 “f”,位数也可以作为输入,指定小数点后的整数数量。整数乘以100,然后应用formatC方法,直到数字的数量。最后,使用paste0()方法,”%”符号被附加在最后输出。
# creating a function to compute percentage
percent <- function(num, digits = 2, ...) {
percentage <-formatC(num * 100, format = "f", digits = digits, ...)
# appending "%" symbol at the end of
# calculate percentage value
paste0(percentage, "%")
}
# defining a vector
vec <- c(0.76485, 1.34, -0.6, 1, 0.0284)
print ("Percentage conversion to three decimal places")
# rounding off the numbers to 3 places
# of decimal
percent(vec, 3)
print ("Percentage conversion to two decimal places")
# rounding off the numbers to 2 places
# of decimal
percent(vec)
输出
[1] "Percentage conversion to three decimal places"
[1] "76.485%" "134.000%" "-60.000%" "100.000%" "2.840%"
[1] "Percentage conversion to two decimal places"
[1] "76.48%" "134.00%" "-60.00%" "100.00%" "2.84%"