以R表示的百分比格式表

以R表示的百分比格式表,r,rstudio,knitr,R,Rstudio,Knitr,我想要一个百分比表,将值格式化为百分比,并以一种好的格式显示它们。我正在使用RStudio和编织到PDF,如果这很重要的话 我看过其他关于这方面的帖子,但没有一篇看起来干净,也不太好用 例如,下面的apply语句的格式是百分比,但是,它去掉了年份,并用引号括住了表格。我可以通过使用kable来修复这些引用,但这似乎是一个非常常见的问题,有一个包或技巧可以解决这个问题 任何帮助都将不胜感激 myTable <- structure(c(.20, .10, .25, .10,

我想要一个百分比表,将值格式化为百分比,并以一种好的格式显示它们。我正在使用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)

myTable您可以使用表中的属性创建一个新矩阵,然后强制使用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文件,我想提到的是,有一个名为
xtable
的R包可以帮助创建表。例如,你可以写

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

xtable(formatted_table)

formatted_table
'rownames谢谢,您以前的解决方案有效,我将尝试一下这个,我相信它也有效。有了像ggplot2、ggvis、dplyr等所有精巧的软件包,我很惊讶没有什么东西可以传递给表和一些格式选项(小数、%或$marker、千分隔符等)。好的,请注意,前面的解决方案与上面的解决方案相同,只是没有
as.data.frame()
包装器