Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format table of percentages in R

Tags:

r

rstudio

knitr

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)
like image 287
John Tarr Avatar asked Nov 28 '25 11:11

John Tarr


1 Answers

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%
like image 73
Rich Scriven Avatar answered Nov 29 '25 23:11

Rich Scriven