R Cook Book
tropf
ABSTRACT
My personal recipes when using R .
1. Intro
I use R mainly for plotting and some data post-process-
ing. This document collects some tricks I encountered and
use.
For plotting I use ggplot2 , which ist assumed to exist in these ex-
amples. A variable p is typically a ggplot2 plot object.
2. Hiding Legend, but Preserving its Space
To hide a legend, but still take up its space (e.g. to
build plots over multiple instances) add the following to
the legend. Adjust the aesthetic used.
p <- p +
guides(fill=guide_legend(override.aes=list(fill=NA))) +
theme(legend.text=element_text(color="#00000000"),
legend.title=element_text(color="#00000000"))
3. aggregate() with more than one output value
To aggregate with multiple outputs, use the following
snippet. Note that this only works if all outputs have the
same type.
2 October 2024
-2-
aggrs <- aggregate(to_be_summarized ~ category,
df,
function(v){c(mean=mean(v), sd=sd(v), min=min(v), max=max(v))})
extra_df <- data.frame(aggrs$to_be_summarized)
aggrs$to_be_summarized <- NULL
colnames(extra_df) <- paste("to_be_summarized", colnames(extra_df), sep=".")
aggrs <- cbind(aggrs, extra_df)
rm(extra_df)
2 October 2024