如何将 scales::percent 或 scales::percent_format() 应用于 R 中的 prop.table 以将数字格式化为百分比
How to apply scales::percent or scales::percent_format() to prop.table in R to format numbers as percentages
考虑以下示例:
tab <- table(mtcars$vs, mtcars$cyl, dnn = c("vs", "cylinder"))
prop.table(tab)
# cylinder
# vs 4 6 8
# 0 0.03125 0.09375 0.43750
# 1 0.31250 0.12500 0.00000
round(prop.table(tab)*100, 1)
# cylinder
# vs 4 6 8
# 0 3.1 9.4 43.8
# 1 31.2 12.5 0.0
期望的输出:
# cylinder
# vs 4 6 8
# 0 3.1% 9.4% 43.8%
# 1 31.2% 12.5% 0.0%
scales::percent(round(prop.table(tab)))
不 工作,因为 plyr::round_any()
没有适用的方法应用于 class table
的对象.
我知道我缺少一个简单的解决方法。或者也许对 plyr::round_any()
的简单包装器或拉取请求可以为每个人解决这个问题?
pt <- percent(c(round(prop.table(tab), 3)))
dim(pt) <- dim(tab)
dimnames(pt) <- dimnames(tab)
这应该有效。 c
用于将 table 或矩阵转换为向量的 属性。
替代使用sprintf
:
pt <- sprintf("%0.1f%%", prop.table(tab) * 100)
dim(pt) <- dim(tab)
dimnames(pt) <- dimnames(tab)
如果你想要 table 不带引号,那么你可以使用例如:
print(pt, quote = FALSE, right = TRUE)
prop <- round(prop.table(tab)*100, 1)
x <- paste(prop, "%", sep="")
print(matrix(x, nrow = 2, ncol = 3), quote = FALSE)
# [,1] [,2] [,3]
# [1,] 3.1% 9.4% 43.8%
# [2,] 31.2% 12.5% 0%
考虑以下示例:
tab <- table(mtcars$vs, mtcars$cyl, dnn = c("vs", "cylinder"))
prop.table(tab)
# cylinder
# vs 4 6 8
# 0 0.03125 0.09375 0.43750
# 1 0.31250 0.12500 0.00000
round(prop.table(tab)*100, 1)
# cylinder
# vs 4 6 8
# 0 3.1 9.4 43.8
# 1 31.2 12.5 0.0
期望的输出:
# cylinder
# vs 4 6 8
# 0 3.1% 9.4% 43.8%
# 1 31.2% 12.5% 0.0%
scales::percent(round(prop.table(tab)))
不 工作,因为 plyr::round_any()
没有适用的方法应用于 class table
的对象.
我知道我缺少一个简单的解决方法。或者也许对 plyr::round_any()
的简单包装器或拉取请求可以为每个人解决这个问题?
pt <- percent(c(round(prop.table(tab), 3)))
dim(pt) <- dim(tab)
dimnames(pt) <- dimnames(tab)
这应该有效。 c
用于将 table 或矩阵转换为向量的 属性。
替代使用sprintf
:
pt <- sprintf("%0.1f%%", prop.table(tab) * 100)
dim(pt) <- dim(tab)
dimnames(pt) <- dimnames(tab)
如果你想要 table 不带引号,那么你可以使用例如:
print(pt, quote = FALSE, right = TRUE)
prop <- round(prop.table(tab)*100, 1)
x <- paste(prop, "%", sep="")
print(matrix(x, nrow = 2, ncol = 3), quote = FALSE)
# [,1] [,2] [,3]
# [1,] 3.1% 9.4% 43.8%
# [2,] 31.2% 12.5% 0%