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.