4
votes

Reading https://twitter.com/hadleywickham/status/719542847045636096 I understand that the purrr approach should basically replace do.

Hence, I was wondering how I would use purrr to do this:

library(dplyr)
d <- data_frame(n = 1:3)
d %>% rowwise() %>% do(data_frame(x = seq_len(.$n))) %>% ungroup()
# # tibble [6 x 1]
#       x
# * <int>
# 1     1
# 2     1
# 3     2
# 4     1
# 5     2
# 6     3

The closest I could get was something like:

library(purrrr)
d %>% mutate(x = map(n, seq_len))
# # A tibble: 3 x 2
#       n         x
#   <int>    <list>
# 1     1 <int [1]>
# 2     2 <int [2]>
# 3     3 <int [3]>

map_int would not work. So what is the purrrr way of doing it?

2
I think you need tidyr::unnest at the end of the chain. I don't know if that's the "purrr way", but it is a way.aosmith

2 Answers

6
votes

You could do the following:

library(tidyverse)
library(purrr)
d %>% by_row(~data_frame(x = seq_len(.$n))) %>% unnest()

by_row applies a function to each row, storing the result in nested tibbles. unnest is then used to remove the nesting and to concatenate the tibbles.

1
votes

Using pmap() removes the need for nesting and unnesting.

library(tidyverse)
d %>% pmap_df(~data_frame(x = seq_len(.)))