Format table of percentages in R

左心房为你撑大大i 提交于 2020-01-05 01:38:24

问题


I want to take a table of percentages, format the values as percentages and display them in a nice format. I'm using RStudio and knitting to PDF if that matters.

I have seen other posts about this, but none of them seem clean, and don't really work well.

For instance, the apply statement below does format as percent, however, it strips the years off, and surrounds the table in quotes. I can fix the quotes by using kable, but it just seems like this is a common enough problem that there is a package or trick for this.

Any help would be greatly appreciated.

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)

回答1:


You could create a new matrix using the attributes from the table, then coerce to data.frame. No apply() looping necessary.

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%



回答2:


In case you were writing an .rnw file, I wanted to mention that there is an R package that helps with table creation called xtable. For example, you could write

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

xtable(formatted_table)

in a knitr chunk and set the chunk option results = 'asis' so that you can get a latex table directly.



来源:https://stackoverflow.com/questions/32382874/format-table-of-percentages-in-r

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