Reputation: 1057
I want to create a tibble with ID (iter
) and randomly generated data.
iter data
<int> <list>
1 1 <dbl [5]>
2 2 <dbl [5]>
3 3 <dbl [5]>
I tried two types of codes and only one of them gives the expected result, but I am not sure why it is, because the only difference is generating data inside tibble()
or not.
iter <- 2 ; n <- 5 ; mu <- 1
gen_data <- function(x){ # randomly draw from Exponential function
return(rexp(n, rate=1/mu))
}
# Works (different values each time)
data <- lapply(1:iter, gen_data)
tibble(iter = 1:iter,
data = data) %>% unnest(data)
# Doesn't work (+ there is a warning)
tibble(iter = 1:iter,
data = lapply(1:iter, gen_data)) %>% unnest(data)
Upvotes: 2
Views: 70
Reputation: 10671
When you call lapply()
in the second expample that doesn't work, you need to be referencing iter
only by it's name instead of trying to re-build a vector.
tibble(iter = 1:iter,
data = lapply(iter, gen_data)) %>% unnest(data)
This is because tibble()
is looking for variables by name within it's context and iter
already exists there as c(1,2)
. The warning comes from you passing two element to :
which complains, then moves ahead using the first element.
Upvotes: 3