Search code examples
rtidyrtibble

add five items on list to each value in column of dataframe


Not really sure how to phrase the title, but what I have a list of names in a dataframe and I would like to add five items from a list to each name such that each name and one item is a row. So,

Name 1, Item1

Name 1, Item2

Name 1, Item3

Name 1, Item4 

Example data:

testdata<-as_tibble(c("Steve","Paul","Mary"))
product<-c("Item1","Item2","Item3","Item4","Item5")

Solution

  • We may need crossing

    library(tidyr)
    crossing(testdata, product)
    

    -output

    # A tibble: 15 x 2
       value product
       <chr> <chr>  
     1 Mary  Item1  
     2 Mary  Item2  
     3 Mary  Item3  
     4 Mary  Item4  
     5 Mary  Item5  
     6 Paul  Item1  
     7 Paul  Item2  
     8 Paul  Item3  
     9 Paul  Item4  
    10 Paul  Item5  
    11 Steve Item1  
    12 Steve Item2  
    13 Steve Item3  
    14 Steve Item4  
    15 Steve Item5