Keep trailing zeros for percents only

旧城冷巷雨未停 提交于 2019-12-23 16:03:27

问题


Given the following example:

library(pander)
tableAbs <- Titanic[1, 1, , ]
tablePct <- round(prop.table(tableAbs) * 100, 2)
table <- cbind(tableAbs, tablePct)
pander(table)

----------------------------------
  &nbsp;     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)

------------------------------------
  &nbsp;      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)

---------------------------
&nbsp;   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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!