Consider the following problem: I have a function with multiple scalar parameters, and I wish to visualise their influence on the result (a data.frame). My favourite construct for this is plyr::mdply, as illustrated below:
weibull <- function(alpha, lambda, time){
data.frame(time = time, value = alpha*lambda*(time^(alpha-1)))
}
library(plyr)
library(ggplot2)
params <- expand.grid(lambda = c(1, 2, 4, 8, 16), alpha = c(0.5, 1))
all <- mdply(params, weibull, time = seq(0, 2, length=100))
ggplot(all, aes(time, value, colour=factor(lambda)))+
facet_wrap(~alpha,scales="free", ncol=2) + geom_line()
It's very concise and expressive. Now, have not found the equivalent one-step solution in the tidyverse.
My current strategy is the following,
weibull <- function(alpha, lambda, time){
data.frame(time = time, value = alpha*lambda*(time^(alpha-1)))
}
library(ggplot2)
library(tidyverse)
params <- tidyr::crossing(lambda = c(1, 2, 4, 8, 16), alpha = c(0.5, 1))
params %>%
dplyr::mutate(purrr::pmap(., .f = weibull, time = seq(0, 2, length=100))) %>%
tidyr::unnest() %>%
ggplot(aes(time, value, colour=factor(lambda)))+
facet_wrap(~alpha,scales="free", ncol=2) + geom_line()
I was hoping initially something like params %>% purrr::pmap_df(.f = weibull, time = seq(0, 2, length=100))
would do the job, but it does not keep track of the original parameters.
Another option might be to use the .id
variable to merge the original params with the results, but that's a non-trivial extra step.