问题
Given the following example:
library(pander)
tableAbs <- Titanic[1, 1, , ]
tablePct <- round(prop.table(tableAbs) * 100, 2)
table <- cbind(tableAbs, tablePct)
pander(table)
----------------------------------
No Yes No Yes
----------- ---- ----- ----- -----
**Child** 0 5 0 2.78
**Adult** 118 57 65.56 31.67
----------------------------------
I would like to keep all trailing zeros on that 0
percentage over there, so this is what I do:
panderOptions("keep.trailing.zeros", TRUE)
pander(table)
------------------------------------
No Yes No Yes
----------- ------ ----- ----- -----
**Child** 0.00 5.00 0.00 2.78
**Adult** 118.00 57.00 65.56 31.67
------------------------------------
The problem is now that even the absolute frequencies have .00
attached to them. Since those are natural numbers, it makes little sense to keep those trailing zeros. How do I do this?
回答1:
Thanks to rawr in the comments.
You can use format
to keep the trailing zeros. This converts the rounded values to character
while preserving the dimensions of the table.
tablePct <- format(round(prop.table(tableAbs) * 100, 2))
edit
Seems to work okay with xtabs
class
mtcars$am[mtcars$vs == 1] <- 0
x <- xtabs(~ am + vs, data=mtcars)
tab <- format(round(100*prop.table(x), 2))
tab <- cbind(x, tab)
pander(tab)
---------------------------
0 1 0 1
------- --- --- ----- -----
**0** 12 14 37.50 43.75
**1** 6 0 18.75 0.00
---------------------------
来源:https://stackoverflow.com/questions/30538920/keep-trailing-zeros-for-percents-only