r - R中的百分比格式表

标签 r rstudio knitr

我想制作一个百分比表,将值格式化为百分比并以漂亮的格式显示它们。如果重要的话,我正在使用 RStudio 并编织成 PDF。

我看过其他关于此的帖子,但它们看起来都不干净,而且效果不佳。

例如,下面的 apply 语句确实将格式设置为百分比,但是它去掉了年份,并用引号将表格括起来。我可以使用 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)

最佳答案

您可以使用表中的属性创建一个新矩阵,然后强制转换为 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%

关于r - R中的百分比格式表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32382874/

相关文章:

r - R bookdown-自定义标题页

r - 需要在R中跳过不同数量的行

r - 列出从R包导出的对象而不附加它

RStudio 不起作用

删除 lapply 中的循环

r - 如何在 Shiny R 文件上传示例中使用 renderDataTable

R - 在 RStudio 上安装 rJava - Amazon Cloud

r - 使用循环在 rmarkdown 中生成文本部分

r - 如何阻止pdf中的bookdown表格 float 到页面底部?

r - 编制 Rmd 文件时如何请求提前退出?