0

I have a list like this:

lst <- list(a = c("y"), b = c("A", "B", "C"), c = c("x1", "x2"))
lst

> lst
$a
[1] "y"

$b
[1] "A" "B" "C"

$c
[1] "x1" "x2"

If I unlist it, I get:

unlist(lst)
> unlist(lst)
   a   b1   b2   b3   c1   c2 
 "y"  "A"  "B"  "C" "x1" "x2" 

How can I get a vector like:

        a         b         c 
      "y" "A, B, C"  "x1, x2" 

Edit: A similar question Convert a list of lists to a character vector was answered previously. The answer proposed by @42_ sapply( l, paste0, collapse="") could be used with a small modification: sapply( l, paste0, collapse=", "). Ronak Shah's sapply(lst, toString) to my question is a little more intuitive.

Zhiqiang Wang
  • 6,206
  • 2
  • 13
  • 27
  • Possible duplicate of [Convert a list of lists to a character vector](https://stackoverflow.com/questions/34624289/convert-a-list-of-lists-to-a-character-vector) – camille Oct 04 '19 at 02:05
  • Thanks. This is slightly different from the previous question. A small modification of those answers would solve my problem. The solution `sapply(lst, toString)` by Ronak Shah is simpler than previous answers. – Zhiqiang Wang Oct 04 '19 at 02:26
  • A separator of `""` and one of `", "` don't seem substantially different – camille Oct 04 '19 at 03:07
  • For new R users, it is difficult to get our heads around functions like `apply` and `paste`. A smallest difference may take a long time to work out. Ronak Shah's solution directly answers my question, simple and straightforward. I have learned something new and useful from this answer which could also help others. – Zhiqiang Wang Oct 04 '19 at 03:42

3 Answers3

2

We can use toString to collapse all the elements in every list into a comma-separated string.

sapply(lst, toString)
#     a       b       c 
#    "y" "A,B,C" "x1,x2" 

which is same as using paste with collapse argument as ","

sapply(lst, paste, collapse = ",")
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

You can also do

unlist(Map(function(x) paste0(x,collapse = ","),lst))

Or

unlist(lapply(lst,function(x) paste0(x,collapse = ",")))

Or use purrr package

purrr::map_chr(lst,paste0,collapse = ",")

yusuzech
  • 5,896
  • 1
  • 18
  • 33
1

we can use map

library(purrr)
library(stringr)
map_chr(lst, str_c, collapse=",")
akrun
  • 874,273
  • 37
  • 540
  • 662