1

I'm looking at a way to turn a named list into a data frame. I have not found similar examples in my search for named list to DF conversion.

My named list is akin to this:

namedList = list(
  A = c("a", "b", "c", "d", "g"),
  B = c("a", "c", "d", "e"))

> namedList

$A
[1] "a" "b" "c" "d" "g"

$B
[1] "a" "c" "d" "e"

I would like to obtain a data frame like this:

> dataFrame

  item names
1 a    A
2 b    A
3 c    A
4 d    A
5 g    A
6 a    B 
7 c    B
8 d    B
9 e    B

Thank you.

M2FKXY
  • 55
  • 5

2 Answers2

2

I'd use the melt function in reshape2:

> reshape2::melt(namedList)
  value L1
1     a  A
2     b  A
3     c  A
4     d  A
5     g  A
6     a  B
7     c  B
8     d  B
9     e  B
> 

Or stack:

> stack(namedList)
  values ind
1      a   A
2      b   A
3      c   A
4      d   A
5      g   A
6      a   B
7      c   B
8      d   B
9      e   B
> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • 1
    Wow, perfect. I obviously didn't look good enough looking at the rapidity of the answer. Thank you (will accept the answer when the timer allows me!). – M2FKXY Nov 05 '21 at 09:49
  • Please search for existing answers before answering. – zx8754 Nov 05 '21 at 09:50
0

Try

tmp=unlist(namedList)
data.frame("item"=tmp,"names"=substr(names(tmp),1,1))

   item names
A1    a     A
A2    b     A
A3    c     A
A4    d     A
A5    g     A
B1    a     B
B2    c     B
B3    d     B
B4    e     B
user2974951
  • 9,535
  • 1
  • 17
  • 24