Skip to content

Instantly share code, notes, and snippets.

@mikelove
Last active October 9, 2015 15:09
Show Gist options
  • Save mikelove/6be2994ed055f2c04f05 to your computer and use it in GitHub Desktop.
Save mikelove/6be2994ed055f2c04f05 to your computer and use it in GitHub Desktop.
nrep <- 100
d <- expand.grid(n=c(3,5,10,20), type=c("normal","t"))
d <- d[rep(seq_len(nrow(d)),each=nrep),]
simulate <- function(n, type) {
if (type == "normal") {
dat <- rnorm(n)
} else {
dat <- rt(n, df=3)
}
dat
meanerr <- abs(mean(dat) - 0)
medianerr <- abs(median(dat) - 0)
c(mean=meanerr, median=medianerr)
}
library(purrr)
library(dplyr)
# for each row, take columns 'n' and 'type' and feed these
# to simulate(), then stash the result as a list in the 'errs'
# column. then i unpack the list as two columns of doubles
# (maybe there's a better way to do unpacking)
# but note that you can stash anything in a cell in the data frame,
# even complex data objects like data frames.
d2 <- d %>% mutate(
errs = map2(n, type, simulate),
mean = map_dbl(errs, `[`, 1),
median = map_dbl(errs, `[`, 2)
)
d2 <- select(d2, -errs)
d2$n <- factor(d2$n)
library(reshape)
m <- melt(d2, id.vars=c("n","type"))
library(ggplot2)
ggplot(m, aes(x=n, y=value, col=variable)) + geom_boxplot() +
facet_wrap(~ type) + ylim(0,2)
@mikelove
Copy link
Author

this is probably not the best purrr example. note that you can put anything in the data frame, here i just store two numbers, but you can put a data object as a cell in the data frame, e.g. another data frame.

for more see blogpost:
http://blog.rstudio.org/2015/09/29/purrr-0-1-0/

or pkg description:
https://github.com/hadley/purrr/blob/master/README.md

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment