I'm trying to find a way to unnest the group of string across columns but keep all the string in the original row. Take the example dataset starwars from dplyr as it has similar strcuture of my dataset.
The starwars dataset has 3 nested columns of films, vehicles, starships. The common approach is to do a unnest_longer so we unnest the group of string into multiple rows - each row contains one piece of the string. However, I'd prefer to keep all the ungrouped string in the original row.
The alternative approach is to use rowwise() and mutate with paste. This works but my dataset has 15 nested columns so I'd have to type 15 line of mutate with paste. That's a bit tedious.
df <- dplyr::starwars %>%
rowwise() %>%
mutate(films = paste(films, collapse=', '),
vehicles = paste(vehicles, collapse=', '),
starships = paste(starships, collapse=', '))
My current thinking is to come up with a wrap function and perhaps I can do it through purrr at scale. But my poor function writing is not working - perhaps I am not too familiar with the dplyr hood.
ungroup_string <- function(data, x){
a <- rowwise(data)
a %>% mutate(x = paste(x, collapse=','))
}
Any way I can do this ungroup string across a number of columns?