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)
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 writein a knitr chunk and set the chunk option results = 'asis' so that you can get a latex table directly.
You could create a new matrix using the attributes from the table, then coerce to data.frame. No
apply()
looping necessary.