Question R string manipulation, remove duplicates and merge/aggregate

Viewed 82

I have a question regarding to R and changing strings. I want for the column taste, that every row has only one name and that duplicates are removed. Then I also want the sweets of duplicated tastes merged.I included before and after pictures as well. How can I change that not manually but with something like aggregate or splitstring? The before and after pictures show how it should look like.

    taste=c("Smarties, Strawberry","Smarties")
    sweets=c("IceCream","Chocolate")
    Dessert=data.frame(taste,sweets)

Before:
https://i.stack.imgur.com/FQAW2.png

After:
https://i.stack.imgur.com/jVidE.png

1 Answers

We can use separate_rows on the 'taste' column to split the elements by the delimiter ,, then grouped by 'taste', paste the 'sweets' in summarise

library(dplyr)
library(tidyr)
Dessert %>%
    separate_rows(taste) %>% 
    group_by(taste) %>%
    summarise(sweets = toString(sweets))
# A tibble: 2 x 2
#  taste      sweets             
#* <chr>      <chr>              
#1 Smarties   IceCream, Chocolate
#2 Strawberry IceCream           

Or in base R, use strsplit to split the 'taste' into a list of vectors, set the names of the list with the 'sweets' column, convert to a two column data.frame with stack and use aggregate to do a group by paste (toString - paste(., collapse=', '))

aggregate(ind ~ values, stack(setNames(strsplit(as.character(Dessert$taste), 
         ",\\s*"), Dessert$sweets)), FUN = toString)
Related