Format table of percentages in R

2019-07-13 03:32发布

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)

标签: r rstudio knitr
2条回答
走好不送
2楼-- · 2019-07-13 03:54

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.

查看更多
闹够了就滚
3楼-- · 2019-07-13 04:05

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%
查看更多
登录 后发表回答