Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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 s, the 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.
_and_grad is changing the s and coloring the cells with a gradient of colors based on cell values.
_and_bar is changing the s and coloring the cells with a bar of a given color, with bar length based on cell values.
_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")), "-family" = "verdana", "-size" = 10)) _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)), "-family" = "verdana", "-size" = 10)) myhtml <- format_table(data, list(id=_and_grad,x=_and_bar)) write(myhtml,outfile)
Now, the only horrible thing left are the header s. 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=\"-family: verdana; -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.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.