user28575 user28575 - 24 days ago 12
R Question

generate multiple data for each row with tidyverse

I have a list of variable named theta and want to draw n number of random variable from using each theta.

S = 5
n = 5
test = tibble(
s = 1:S,
theta = rgamma(S, shape = 10*s, rate = 50)
) %>%
mutate(data = rexp(n, theta))


ideally, I want my result be something like this:

S theta data
1 some value [a list with n number]
...


then expand it into a tibble:

S theta d1 d2 d3 .. dn
...


Hope this is clear.
Thanks.

Answer Source

If we need a list then, we can use map to loop through the each element of 'theta' and get the rexp in a list

library(tidyverse)
test1 <- test %>% 
            pull(theta) %>%
            map(~rexp(n, .)) %>% 
            mutate(test, data = .)
str(test1$data)
#List of 5
# $ : num [1:5] 5.88 7.94 1.64 3.3 11.25
# $ : num [1:5] 4.5942 0.5424 1.7479 0.0469 0.9573
# $ : num [1:5] 1.192 2.447 0.239 1.497 2.359
# $ : num [1:5] 1.2323 0.0996 1.5778 0.1278 0.6982
# $ : num [1:5] 0.15 0.733 0.19 3.548 2.08

The list column can be unnested

test1 %>%
      unnest(data)

data

S <- 5
n <- 5

test <- tibble(
  s = 1:S,
  theta = rgamma(S, shape = 10*s, rate = 50)
)