-1

i have the following dataframe,

id food drink 
1  chip coke, wine, punch
2  eggs pepsi, water
3  pie  water, wine, orange juice

I want to know how i can get the following dataframe instead:

id food drink 
1  chip coke 
1  chip wine 
1  chip punch 
2  eggs pepsi 
2  eggs water 
3  pie  water 
3  pie  wine 
3  pie  orange juice

i would like to use something from the tidyverse such as the stringr pacakge - but am stuck at the moment

any ideas how to do this in R?

  • Too complex for beginners - my question easier to understand – DreadPirateRoberts Oct 30 '18 at 15:50
  • 2
    There are 4 answers posted there, 2 of which give several options with several packages. One of those answers is the same as the one you've accepted. Are they all too complicated? – camille Oct 30 '18 at 16:12

2 Answers2

2

We can use separate_rows

library(tidyverse)
separate_rows(df1, drink, sep=", ")
#   id food  drink
#1  1 chip   coke
#2  1 chip   wine
#3  1 chip  punch
#4  2 eggs  pepsi
#5  2 eggs  water
#6  3  pie  water
#7  3  pie   wine
#8  3  pie orange juice

data

df1 <- structure(list(id = 1:3, food = c("chip", "eggs", "pie"),
 drink = c("coke, wine, punch", 
 "pepsi, water", "water, wine, orange juice")), class = "data.frame", 
 row.names = c(NA, -3L))
akrun
  • 874,273
  • 37
  • 540
  • 662
0

another way you can solve this problem is with tidytext

library(tidytext)
unnest_tokens(df, drink)

This wil split that text column up into words. You can also use it for other unnesting but this works. See more info here: https://www.tidytextmining.com/tidytext.html#the-unnest_tokens-function

Roel Hogervorst
  • 299
  • 3
  • 13