Merging list of lists with comma separated in R

Viewed 182

I have a data set like that

Reproducible data

test <- list(c("1"),c("2"),c("3"),c(c("a"),c("b")),c("d"))

Desired output is:

1
2
3
a,b
d

I have tried

output <- do.call(rbind, test)
4 Answers

You can use toString to collapse every element in the list.

out <- data.frame(result = sapply(test, toString))
out
#  result
#1      1
#2      2
#3      3
#4   a, b
#5      d

We can use tidyverse methods

  1. Loop over the list with map
  2. Paste the elements using str_c
  3. Return a single column dataset by adding the suffix _dfr in map
library(dplyr)
library(purrr)
library(stringr)
map_dfr(test, ~ tibble(col1 = str_c(.x, collapse=",")))
# A tibble: 5 x 1
  col1 
  <chr>
1 1    
2 2    
3 3    
4 a,b  
5 d    

Actually you are already close to your goal. Maybe the code below can help you

> do.call(rbind, Map(toString, test))
     [,1]
[1,] "1"
[2,] "2"
[3,] "3"
[4,] "a, b"
[5,] "d"

Maybe this could help too beside all the very good answers you received:

test |> 
  lapply(\(x) paste(x, collapse = ",")) |>
  cbind()

     [,1] 
[1,] "1"  
[2,] "2"  
[3,] "3"  
[4,] "a,b"
[5,] "d" 
Related