How to apply scales::percent or scales::percent_format() to prop.table in R to format numbers as percentages

6.7k views Asked by At

Consider the following example:

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

Desired output:

#    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))) does not work because there is no applicable method for plyr::round_any() applied to an object of class table.

I know I'm missing a simple workaround. Or perhaps a simple wrapper or pull request to plyr::round_any() could fix this for everyone?

2

There are 2 answers

3
Nick Kennedy On BEST ANSWER
pt <- percent(c(round(prop.table(tab), 3)))
dim(pt) <- dim(tab)
dimnames(pt) <- dimnames(tab)

This should work. c being used here for its property of turning a table or matrix into a vector.

Alternative using sprintf:

pt <- sprintf("%0.1f%%", prop.table(tab) * 100)
dim(pt) <- dim(tab)
dimnames(pt) <- dimnames(tab)

If you want the table written without quotes, then you could use for example:

print(pt, quote = FALSE, right = TRUE)
2
rmuc8 On
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%