0

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.

4 Answers 4

1
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))
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

The two codes give different results
1

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

Comments

1

Using complete

library(dplyr)
library(tidyr)
x %>% 
   group_by(name) %>% 
   complete(seqnbr = seqnbr:10) %>%
   ungroup

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.