0
votes

Getting my feet wet with purrr.

I'm evaluating different combinations of parameters for a beta distribution and I'm trying to pass a vector of x values and the parameters for the distribution.

See the code below:

library(tidyr)
library(purrr)
library(dplyr)

x <- seq(0.01, 0.99, 0.01)
alpha <-  c(0.1, 0.5, 1:5, 10)
beta <-  c(0.5, 1, 2, 5)


df <- expand.grid(alpha = alpha, beta = beta, x = x) %>% 
  nest(x) %>%
  mutate(plotdata = pmap(list(data$x, alpha, beta), dbeta)) %>%
  unnest()

What's the right syntax for pmap in this case?

1

1 Answers

0
votes

Let's get the first case as an example.

 x = 0.01
 alpha = 0.1
 beta = 0.5

dbeta(shape1 = alpha, shape2 = beta, x = x)
# [1] 5.600381

A second example would be:

x = 0.01
alpha = 0.5  
beta = 0.5 

dbeta(shape1 = alpha, shape2 = beta, x = x)
# [1] 3.199135

If this is the output you are expecting, then we could generalize it:

x <- seq(0.01, 0.99, 0.01)
alpha <-  c(0.1, 0.5, 1:5, 10)
beta <-  c(0.5, 1, 2, 5)

df <- expand.grid(alpha = alpha, beta = beta, x = x)

args_beta <- with(df, list(x = x, shape1 = alpha, shape2 = beta))
args_beta %>% 
  pmap(dbeta) %>% 
  unlist() %>% 
  as.data.frame() %>% 
  cbind(df, .)

Then the output would be:

alpha beta    x            .
1   0.1  0.5 0.01 5.600381e+00
2   0.5  0.5 0.01 3.199135e+00
3   1.0  0.5 0.01 5.025189e-01
4   2.0  0.5 0.01 7.537784e-03
5   3.0  0.5 0.01 9.422230e-05
6   4.0  0.5 0.01 1.099260e-06