4

I am trying to understand invoke_map. In this case I simulate 30 bivariate random normal observations and assign them to a grouping field for later use simulating a random intercept and slope.

Everything is straight forward until I have to unnest the matrix column.

The main thing is that the mutate(u1,u2) line seems more complicated than it needs to be. What should I do instead?

library(dplyr)
library(mvtnorm)
N <- 30
# Simulate two correlated random normal variables into a tibble
var_u1    <-  0.0005
var_u2    <-  0.010
cov_u1_u2 <- -0.0002

SIGMA <-  matrix(c(var_u1, cov_u1_u2, cov_u1_u2, var_u2), nrow = 2) 
sim_u <- dplyr::tribble(
  ~f, ~params,
  'rmvnorm', list(n = N, mean = c(0,0), sigma = SIGMA)  
)
u <- sim_u %>% 
  mutate(u = purrr::invoke_map(f,params))   %>% 
  mutate(u0 =  purrr::map(u,`[`,i=,j=1),
         u1 =  purrr::map(u,`[`,i=,j=2))     %>% 
  tidyr::unnest(u0,u1) %>% 
  mutate(lab = 1:N) %>% 
  select(lab,u0,u1)
u
Harlan Nelson
  • 1,394
  • 1
  • 10
  • 22

0 Answers0