在 R 中将数字格式化为百分比
在本文中,我们将了解如何在 R 编程语言中将数字格式化为百分比。
方法一:使用formattable包
“formattable”包提供了创建可格式化向量和数据框对象的方法。可以使用以下命令安装 R 中的这个包并将其加载到工作空间中:
install.packages("formattable")
该包中的 percent() 方法用于将数值向量表示为百分比格式。
Syntax: percent(vec, digits, format = “f”, …)
Arguments :
- vec – The vector to convert to percentage format
- digits – The digits to have after decimal point. By default, the number of digits is equivalent to 2.
- format – format type string passed to the method format.
代码:
R
# 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)
R
# loading the required libraries
library("scales")
# creating a vector
vec <- c(0.76485, 1.34, -0.6, 1)
print ("Percentage conversion")
percent (vec)
R
# 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 : 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() 方法用于将数值向量表示为百分比格式。
Syntax: percent(vec)
Arguments : vec – The vector to convert to percentage format
代码:
电阻
# 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%"
方法三:使用自定义函数
用户定义的方法可用于将数字转换为百分比格式。此函数使用的格式说明符是“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%"