Knitting tables with kable

The kable function from the knitr package allows to display nicely formatted tables using R Markdown, as explained here. I recently encountered unexpected behaviour of kable when calling it from lapply or a function, which led to this post on StackOverflow. The answers were very detailed and enlightening, and I invite you to read them. They could be summarized in two points: be aware of side-effects, and prefer cat (with new lines) to print.

Advertisements

Add summary label in stacked bar chart using ggplot

The script below illustrates how to add one label per stack in a stacked bar chart using ggplot in R. In this case, labels indicate the sum of values represented in each bar stack. The idea is to create as many labels as bars, but assign text to only one label per stack, then plot labels according to stack height.

Merging in R

A common task I happen to do in R is merging tables (for instance, using gene symbol as a join) and renaming columns with a suffix to indicate their table of origin. Below is a function that automatizes most of the process, taking any number of dataframes as input. It is also posted on GitHub.