Home > Software design >  How to summarise a column in a grouped tibble into a list of unique values
How to summarise a column in a grouped tibble into a list of unique values

Time:11-20

Suppose I run the following code:

library(tidyverse)
tbl <- tibble::tribble(
          ~name,       ~fruit,
          "dan",      "apple",
          "dan",      "apple",
          "dan",     "banana",
       "george",     "banana",
       "george", "watermelon",
       "george",     "banana",
       "lauren",       "kiwi",
       "lauren",       "kiwi",
       "lauren",       "kiwi"
       )

tbl %>%
    group_by(name) %>%
    summarise(fruits = unique(list(fruit)))

This is the table I get:

enter image description here

Why is it still displaying non-unique fruits in each list?

CodePudding user response:

Change

tbl %>%
    group_by(name) %>%
    summarise(fruits = unique(list(fruit)))

to

tbl %>%
    group_by(name) %>%
    summarise(fruits = list(unique(fruit)))

Output:

name fruits
dan apple , banana
george banana , watermelon
lauren kiwi
  • Related