ThomasW
ThomasW

Reputation: 11

Converting an R dataframe of lists into a dataframe of strings

I have a dataframe generated with R in which the individual fields are occupied by lists. Here is an example:

col1 <- list (c("a", "b", "c"), c("d", "e", "f", "g"))

col2 <- list (c("h", "i"), "j")

df = cbind (col1, col2) %>% as.data.frame()

What would be a good way to change the lists in each field into strings?

Upvotes: 0

Views: 81

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173858

If you want the vectors in each data frame cell concatentated into a single string with comma separators (since you don't specify this in your question), you can do:

df[] <- lapply(df, function(x) sapply(x, function(y) paste(y, collapse = ', ')))

df
#>         col1 col2
#> 1    a, b, c h, i
#> 2 d, e, f, g    j

Or, using tidyverse syntax

library(dplyr)

df %>% 
  mutate(across(.fns = ~ map(.x, ~ paste(.x, collapse = ', '))))
#>         col1 col2
#> 1    a, b, c h, i
#> 2 d, e, f, g    j

Created on 2023-01-21 with reprex v2.0.2

Upvotes: 1

Related Questions