I used to think that making nice table in R is not worth the effort. However, after changing my mind for the billionth time on relatively large tables for a paper and do not wanting to reformat them again from scratch, I gave a try to the formattable package, and I liked it very much.
I post here some basic formats I learnt from the web.
Note: I usually work on remote servers with no/limited graphical capabilities (no X11, basically), and for me the formattable function doesn’t work. I use the format_table instead and write the html code to a file, which I then open. However, I never noticed differences in the behavior of format_table from what more expert users showed for fromattable.
Let’s create a table:
library(formattable) library(knitr) outfile<-"test.html" data<-data.frame(id=1:10,x=round(rnorm(10,100,25))) myhtml <- format_table(data) write(myhtml,outfile)
This is the output
Ok. It’s a table. I want to change the fonts, the font size, AND format the cell based on their values. It’s possible, but it was not easy for me to find a way to do that. See my post on stackoverflow with link to the demo where formattable author showed how to do that.
I will create two formatters.
font_and_grad is changing the fonts and coloring the cells with a gradient of colors based on cell values.
font_and_bar is changing the fonts and coloring the cells with a bar of a given color, with bar length based on cell values.
font_and_grad <- formatter("span", style = x ~ style( display = "block", direction = "rtl", "border-radius" = "4px", "padding-right" = "2px", "background-color" = csscolor(gradient(as.numeric(x),min.color="yellow",max.color="darkorange")), "font-family" = "verdana", "font-size" = 10)) font_and_bar <-formatter("span", style = x ~ style( display = "inline-block", direction = "rtl", "border-radius" = "4px", "padding-right" = "2px", "background-color" = csscolor("lightgreen"), width = percent(proportion(x)), "font-family" = "verdana", "font-size" = 10)) myhtml <- format_table(data, list(id=font_and_grad,x=font_and_bar)) write(myhtml,outfile)
Now, the only horrible thing left are the header fonts. I had troubles accomplishing this, and at the end I decided that I would simply change the html code.
myhtml<-gsub(" <th style=\"text-align:right","<th style=\"font-family: verdana; font-size: 10; text-align:right",myhtml) write(myhtml,outfile)
Maybe not the best approach, but it worked! Another approach has been suggested on stackoverflow, but it wasn’t very well suited for me. As usual, comments and suggestions are welcome.