mutate rnorm with multiple column output

Viewed 233

I would like to create random variables using rnorm() with the mean and sd specified in separate columns in a tibble

n <- 2
ti <- tibble(Name = letters[1:10], mean = 1:10, sd = 1:10)

How do I use mutate to add n columns to the tibble with output from rnorm(n, mean, sd) for every row?

(I know I can do this in base R, but am curious to learn how this works using dplyr)

1 Answers

One dplyr and tidyr option could be:

ti %>%
 rowwise() %>%
 mutate(col_rnorm = list(setNames(rnorm(n, mean, sd), c("col1", "col2")))) %>%
 unnest_wider(col_rnorm)

  Name   mean    sd  col1    col2
   <chr> <int> <int> <dbl>   <dbl>
 1 a         1     1 -1.73  1.18  
 2 b         2     2  3.86  0.0943
 3 c         3     3  3.54 -0.502 
 4 d         4     4  3.21 -3.90  
 5 e         5     5  3.61  9.48  
 6 f         6     6  7.07 16.1   
 7 g         7     7 17.4   5.95  
 8 h         8     8  5.32 13.6   
 9 i         9     9 19.2  19.8   
10 j        10    10  9.67 11.3 
Related