Simon
Simon

Reputation: 1111

General method to unnest list to strings in R

I previously posted a question about unnesting lists and concatenating.

While the answers there correctly addressed my original question, I have since found that the method does not work on my substantially more complex real dataset. I feel that an entirely new question is required to adequately find and discuss a solution.

I need a general method that will concatenate both lists and data.frames within a single tibble. Below is a more complex MRE in the hope that someone can find a more general solution.

tibble(person = c("Alice", "Bob", "Mary"), 
          colour = list(c("Red", "Green", "Blue"), c("Orange", "Green", "Yellow"), "Blue"),
          drink = list(c("Pepsi", "Coke", "Fanta"), c("Pepsi"), c("Coke", "Fanta")),
          scores = list(c("1", "17", "32"), c("1", "12"), c("5", "16")),
          geometry = data.frame(type = "Point",
                                coordinates = c("1, 2", "2, 3", "1, 5")))

Expected output:

tibble(person = c("Alice", "Bob", "Mary"),
       colour = c("Red, Green, Blue", "Orange, Green, Yellow", "Blue" ),
       drink = c("Pepsi, Coke, Fanta", "Pepsi", "Coke, Fanta"),
       scores = c("1, 17, 32", "1, 12", "5, 16"),
       geometry = c("Point 1, 2", "Point 2, 3", "Point 1, 5"))

Upvotes: 1

Views: 99

Answers (1)

lroha
lroha

Reputation: 34301

You can use mutate_if() to check if a column is a list, then apply a different function depending on whether these lists are data.frames or not:

library(dplyr)
library(purrr)

df %>%
  mutate_if(is.list, ~ if(is.data.frame(.x)) do.call(paste, .x) else map_chr(.x, toString))

# A tibble: 3 x 5
  person colour                drink              scores    geometry  
  <chr>  <chr>                 <chr>              <chr>     <chr>     
1 Alice  Red, Green, Blue      Pepsi, Coke, Fanta 1, 17, 32 Point 1, 2
2 Bob    Orange, Green, Yellow Pepsi              1, 12     Point 2, 3
3 Mary   Blue                  Coke, Fanta        5, 16     Point 1, 5

Upvotes: 1

Related Questions