Is there a purrr equivalent to replicate?

The question is just as stated in the topic header; I'm pretty sure I haven't seen this asked elsewhere.

I have a function which will return a data frame, without arguments. I want to use this to create a nested data frame, which will have a column, each of those elements is a data frame. Being a tidyverse fan, I looked into purrr for something to handle this. I don't see anything which handles this without a slightly ugly hack. Here's some code.

First, the function which creates a data frame. (Not my actual function, obviously.)

make_a_tbl <- function() {
  tibble(x = seq.int(10), y = x^2)
}

I can't use map because map expects an argument. The code below will return an error.

my_tbl <- tibble(
    index = seq.int(10)
  , a_tbl = map(index, make_a_tbl)
)

I could create a dummy function, which will ignore its argument, but this doesn't feel right.

fake_a_make <- function(i) {
  make_a_tbl()
}

my_tbl <- tibble(
    index = seq.int(10)
  , a_tbl = map(index, fake_a_make)
)

But replicate will work:

my_tbl <- tibble(
    index = seq.int(10)
  , a_tbl = replicate(length(index), make_a_tbl(), simplify = FALSE)
)

So, I have functioning code, but curious if there were some tidyverse function that I'm missing.

1 Like

purrr::rerun maybe?

(Edit 2020-06-05: I have come for the future to appreciate the irony of me finding this post through googling after forgetting what the purrr equivalent of replicate was)

5 Likes

Ah, there it is! I missed it tucked away with all of the other "Misc" functions.