I want to concatenate values per group that are now in one column. The following is a short version of the data frame I want to wrangle.
library(tidyverse)
df <- tibble::tribble(
~county, ~party,
"A", "VVD",
"A", "GL",
"A", "Local",
"B", "D66",
"B", "Local"
)
Now I want to create one row per county with all the parties in their own column:
df2 <- tibble::tribble(
~county, ~party1, ~party2, ~party3,
"A", "VVD", "GL", "Local",
"B", "D66", "Local", NA
)
To later concatenate with unite()
and replace the underscores for comma's and Remove the NA's.
df2 %>%
unite(party, c("party1", "party2", "party3")) %>%
mutate(party = gsub("_NA", "", party),
party = gsub("_", ", ", party))
My desired df
output:
county party
<chr> <chr>
1 A VVD, GL, Local
2 B D66, Local