Skip to content

Instantly share code, notes, and snippets.

@mikelove
Created July 19, 2016 23:28
Show Gist options
  • Save mikelove/380d684e0d78f0f00386f612eec96d4f to your computer and use it in GitHub Desktop.
Save mikelove/380d684e0d78f0f00386f612eec96d4f to your computer and use it in GitHub Desktop.
using purrr for simple R simulations
nrep <- 100
d <- expand.grid(n=c(3,5,10,20), sd=c(1,2,3))
d <- d[rep(seq_len(nrow(d)),each=nrep),]
simulate <- function(n, sd) {
rnorm(n=n, mean=0, sd=sd)
}
library(purrr)
library(dplyr)
d2 <- d %>% mutate(
sim = map2(n, sd, simulate),
RMSE = map_dbl(sim, ~sqrt(mean(.^2))),
MAD = map_dbl(sim, ~1.48*median(abs(.)))
)
d2 <- select(d2, -sim)
d2$n %<>% factor
library(reshape)
m <- melt(d2, id.vars=c("n","sd"))
library(ggplot2)
p <- ggplot(m, aes(x=n, y=value, col=variable)) +
geom_boxplot() +
facet_wrap(~ sd)
print(p)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment