1

I would like to collapse a subcategory into a comma-delimited string for display.
This is what I have.

library(tibble)
eats <- tribble(
  ~food,~variety,
  "fruit","cherry",
  "fruit","apple",
  "fruit","peach",
  "nut","cashew",
  "nut","almonds"
)
eats
#> # A tibble: 5 x 2
#>   food  variety
#>   <chr> <chr>  
#> 1 fruit cherry 
#> 2 fruit apple  
#> 3 fruit peach  
#> 4 nut   cashew 
#> 5 nut   almonds

This is what I want:

eats2 <- tribble(
  ~food,~varieties,
  "fruit","cherry, apple, peach",
  "nut","cashew, almond"
)
eats2  
#> # A tibble: 2 x 2
#>   food  varieties           
#>   <chr> <chr>               
#> 1 fruit cherry, apple, peach
#> 2 nut   cashew, almond

This what I've tried:

eats %>% 
  nest(data=variety) %>% 
  mutate(data = paste(data,collapse = ""))
#> # A tibble: 2 x 2
#>   food  data                                                                    
#>   <chr> <chr>                                                                   
#> 1 fruit "list(variety = c(\"cherry\", \"apple\", \"peach\"))list(variety = c(\"~
#> 2 nut   "list(variety = c(\"cherry\", \"apple\", \"peach\"))list(variety = c(\"~

Nope.

eats %>% 
  nest(data=variety) %>% 
  map(~.x %>% mutate(varieties=paste(data,collapse = "")))
#> Error in UseMethod("mutate"): no applicable method for 'mutate' applied to an object of class "character"

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

Also nope. What is the right way to do this? Thanks.

Art
  • 1,165
  • 6
  • 18

2 Answers2

2

You can use the following code using summarise and toString:

library(tibble)
library(dplyr)
eats <- tribble(
  ~food,~variety,
  "fruit","cherry",
  "fruit","apple",
  "fruit","peach",
  "nut","cashew",
  "nut","almonds"
)
eats %>%
  group_by(food) %>%
  summarise(varieties = toString(variety)) %>%
  ungroup()
#> # A tibble: 2 × 2
#>   food  varieties           
#>   <chr> <chr>               
#> 1 fruit cherry, apple, peach
#> 2 nut   cashew, almonds

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

Quinten
  • 35,235
  • 5
  • 20
  • 53
  • That was easier than I thought. Thanks. It shows how my base-R skills have atrophied. I forgot all about toString. – Art Jul 01 '22 at 20:07
2

Like @Quinten's solution, just using paste instead of toString:

library(dplyr)

eats %>%
  group_by(food) %>%
  summarise(varieties = paste(variety, collapse = ", ")) %>%
  ungroup()
  food  varieties           
  <chr> <chr>               
1 fruit cherry, apple, peach
2 nut   cashew, almonds
TarJae
  • 72,363
  • 6
  • 19
  • 66