Home > front end >  Converting an R dataframe of lists into a dataframe of strings
Converting an R dataframe of lists into a dataframe of strings

Time:01-21

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?

BTW, I tried to tap the wisdom of chatGPT, and here are the AI's suggestions (and no, they does not work...):

screenshot

CodePudding user response:

Second attempt with chatGPT, two new solutions suggested by the AI - the second of which solved the problem:

df[] <- apply(df, 1, function(x) sapply(x,toString))

Cool!

CodePudding user response:

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

  • Related