R 中百分比的格式 table

Format table of percentages in R

我想获取 table 个百分比,将这些值格式化为百分比并以合适的格式显示它们。如果重要的话,我正在使用 RStudio 并编织成 PDF。

我看过其他关于此的帖子,但其中 none 看起来很干净,但效果并不好。

例如,下面的 apply 语句确实将格式设置为百分比,但是它去掉了年份,并用引号将 table 括起来。我可以使用 kable 修复引号,但这似乎是一个很常见的问题,因此有一个包或技巧可以解决这个问题。

如有任何帮助,我们将不胜感激。

myTable <- structure(c(.20, .10, .25, .10, 
                       .20, .10, .25, .20, 
                       .20, .10, .25, .30, 
                       .20, .10, .25, .40, 
                       .20, .60, .25, .0), 
            class = "table", 
            .Dim = c(5L, 4L), 
            .Dimnames = structure(list(c("2006", "2007", "2008", "2009", "2010"), 
                                       c("1", "2", "3", "4")), 
                                  .Names = c("", "")))

# Table is fine, but needs decimal shifted and % sign added
myTable

formattedTable <- apply(myTable*100, 2, function(u) sprintf("%.0f%%", u))

# Decimal is shifted and % sign added, but no years, and quotes around text
formattedTable

# Fixes the quotes issue, still no years
kable(formattedTable)

您可以使用 table 中的属性创建一个新矩阵,然后强制转换为 data.frame。无需 apply() 循环。

as.data.frame(matrix(
    sprintf("%.0f%%", myTable*100), 
    nrow(myTable), 
    dimnames = dimnames(myTable)
))
#        1   2   3   4
# 2006 20% 10% 25% 40%
# 2007 10% 25% 30% 20%
# 2008 25% 20% 20% 60%
# 2009 10% 20% 10% 25%
# 2010 20% 10% 25%  0%

如果您正在编写 .rnw 文件,我想提一下 一个帮助 table 创建名为 xtable 的 R 包.例如,您可以写

formatted_table <- as.data.frame(matrix(
   sprintf("%.0f%%", myTable*100),
   nrow(myTable),
   dimnames = dimnames(myTable)
))

xtable(formatted_table)

在 knitr 块中并设置 chunk option 结果 = 'asis' 这样你就可以直接得到乳胶 table。