Skip to content

Instantly share code, notes, and snippets.

@kleinschmidt
Created March 2, 2013 00:36
Show Gist options
  • Save kleinschmidt/5069055 to your computer and use it in GitHub Desktop.
Save kleinschmidt/5069055 to your computer and use it in GitHub Desktop.
How to compute SE of an observed variable and plot errorbars in R using plyr and ggplot.
require(plyr)
require(ggplot2)
# say dat is a data.frame with the predictor x, grouping variables z1, z2, and z3 (factors or discrete numeric values)
# and the observed values are in the variable y. then I would do:
dat.summ <- ddply(dat, .(x, z1, z2, z3), summarise,
y.mean=mean(y), y.se=sd(y)/sqrt(length(y)))
# this is equivalent to
dat.summ <- ddply(dat, .(x, z1, z2, z3), function(d) {
with(d, data.frame(y.mean=mean(y), y.se=sd(y)/sqrt(length(y))))
})
# summarise just provides a nice shortcut.
# then to plot w/ errorbars:
ggplot(dat.summ, aes(x=x, group=z1:z2:z3, y=y.mean)) +
geom_line() +
geom_errorbar(aes(ymin=y.mean-1.96*y.se, ymax=y.mean+1.96*y.se))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment