Reputation: 3321
Goal: I would like to create a numeric list based on the starting value in another column (seqnbr), then unnest it.
In the data below a nested c(1:10)
sequence would begin on the column seqnbr.
x <- tibble(name = c('boo', 'bah', 'bee'),
seqnbr = c(1,2,3))
A tibble: 3 x 2
name seqnbr
<chr> <dbl>
1 boo 1
2 bah 2
3 bee 3
desired result would look like this:
# A tibble: 3 x 3
name seqnbr my_list
<chr> <dbl> <chr>
1 boo 1 list(c(1:10) )
2 bah 2 list(c(2:10) )
3 bee 3 list(c(3:10) )
After this step, I would unnest() to make values explicit.
Tidyverse/purr solutions preferred.
Upvotes: 0
Views: 45
Reputation: 887028
Using complete
library(dplyr)
library(tidyr)
x %>%
group_by(name) %>%
complete(seqnbr = seqnbr:10) %>%
ungroup
Upvotes: 1
Reputation: 79208
You could use reframe
:
library(tidyverse)
reframe(x, my_list = seqnbr:10, .by = name)
# A tibble: 27 × 2
name my_list
<chr> <int>
1 boo 1
2 boo 2
3 boo 3
4 boo 4
5 boo 5
6 boo 6
7 boo 7
8 boo 8
9 boo 9
10 boo 10
# … with 17 more rows
# ℹ Use `print(n = ...)` to see more rows
Upvotes: 1
Reputation: 24722
You can use purrr::map, if you like:
mutate(x, my_list=map(seqnbr, ~.x:10)) %>% unnest_longer(my_list)
Output:
# A tibble: 27 × 3
name seqnbr my_list
<chr> <dbl> <int>
1 boo 1 1
2 boo 1 2
3 boo 1 3
4 boo 1 4
5 boo 1 5
6 boo 1 6
7 boo 1 7
8 boo 1 8
9 boo 1 9
10 boo 1 10
# … with 17 more rows
Upvotes: 1
Reputation: 5137
library(tidyverse)
x <- tibble(name = c('boo', 'bah', 'bee'),
seqnbr = c(1,2,3))
(x_1 <- x |> rowwise() |> mutate(my_list= list(seq(from=seqnbr,
to=10))))
(x_2 <- unnest_longer(x_1,col=my_list))
Upvotes: 1