How to duplicate column rows and fill an added column with one item in list

Viewed 40

I have a dataframe with the following columns:

tester <- data.frame(id = c(123456789, 987654321))
tester$furniture <- list(c("chair"), c("bed", "bench", "barstool"))
tester$count <- c(1,3)

Based on the value in the count column, each row is repeated [count] number of times:

tester[rep(seq_len(dim(tester_2)[1]), tester$count), ]

The number of items in the furniture list will always be equal to the count value

I want to create a new column that contains one item from the list, in order from the first through the last list item. I would manually input what I want in this new column as:

tester$new <- c("chair", "bench", "bed", "barstool")

but this doesn't work now because the dataframe resulting from the above code only technically has two rows.

Any advice would be greatly appreciated!

2 Answers

You could also use the function unchop from tidyr like this:

tester <- data.frame(id = c(123456789, 987654321)) 
tester$furniture <-  list(c("chair"), c("bed", "bench", "barstool")) 
tester$count <- c(1,3)

library(tidyr)
unchop(tester, id:count)
#>          id furniture count
#> 1 123456789     chair     1
#> 2 987654321       bed     3
#> 3 987654321     bench     3
#> 4 987654321  barstool     3

Created on 2022-07-14 by the reprex package (v2.0.1)

And if you want to keep the furniture column you can use this:

tester <- data.frame(id = c(123456789, 987654321)) 
tester$furniture <-  list(c("chair"), c("bed", "bench", "barstool")) 
tester$count <- c(1,3)

library(dplyr)
library(tidyr)
tester %>% 
  mutate(new = furniture) %>%
  unchop(new)
#>          id            furniture count      new
#> 1 123456789                chair     1    chair
#> 2 987654321 bed, bench, barstool     3      bed
#> 3 987654321 bed, bench, barstool     3    bench
#> 4 987654321 bed, bench, barstool     3 barstool

Created on 2022-07-14 by the reprex package (v2.0.1)

You could achieve it with unnest() from tidyr:

tidyr::unnest(tester, furniture)

# # A tibble: 4 × 3
#          id furniture count
#       <dbl> <chr>     <dbl>
# 1 123456789 chair         1
# 2 987654321 bed           3
# 3 987654321 bench         3
# 4 987654321 barstool      3

If you want to preserve the list-column, then

library(tidyverse)

tester %>%
  mutate(new = furniture) %>%
  unnest(new)

# # A tibble: 4 × 4
#          id furniture count new     
#       <dbl> <list>    <dbl> <chr>   
# 1 123456789 <chr [1]>     1 chair   
# 2 987654321 <chr [3]>     3 bed     
# 3 987654321 <chr [3]>     3 bench   
# 4 987654321 <chr [3]>     3 barstool
Related