How can I restructure information contained in a list object in two columns?

7

Considering a list x consisting of% with% vectors. To illustrate the problem I have thought that it has 3 elements, as follows:

>x
$'2751006'
[1] 106.2  75.4  65.4  87.4  76.8 196.4  74.2

$'2751007'
[1]  73.9 110.1 101.3

$'2752006'
[1] 100.0 200.0

How can I restructure the information in this list in% with% of two columns of names X1 and X2:

X1      X2
106.2   2751006
75.4    2751006
65.4    2751006    
87.4    2751006
76.8    2751006
196.4   2751006
74.2    2751006
73.9    2751007
110.1   2751007
101.3   2751007
100.0   2752006   
200.0   2752006
    
asked by anonymous 04.01.2016 / 20:30

3 answers

5

There is a function in the base that does just that, called stack . The hardest part of using it is remembering the name because it's pretty unusual (I've been looking for 10 minutes until I find it):

> li <- list(a = 1:3, b = 4:8, c = 9:10)
> li
$a
[1] 1 2 3

$b
[1] 4 5 6 7 8

$c
[1]  9 10

> stack(li)
   values ind
1       1   a
2       2   a
3       3   a
4       4   b
5       5   b
6       6   b
7       7   b
8       8   b
9       9   c
10     10   c
> unstack(stack(li))
$a
[1] 1 2 3

$b
[1] 4 5 6 7 8

$c
[1]  9 10
    
04.01.2016 / 22:37
3

Another way to do this is as follows:

> library(dplyr)
> x <- list(x = 1:3, y = 6:10, z = 8:13)
> lapply(x, function(x) data.frame(X1 = x)) %>% bind_rows(.id = "X2")
Source: local data frame [14 x 2]

      X2    X1
   (chr) (int)
1      x     1
2      x     2
3      x     3
4      y     6
5      y     7
6      y     8
7      y     9
8      y    10
9      z     8
10     z     9
11     z    10
12     z    11
13     z    12
14     z    13

The function bind_rows of dplyr has the argument .id , when we give it the name of a column, it uses the identifier of the list as the id of each line.

    
04.01.2016 / 22:32
3

You can also use the melt function of the reshape2 package.

Using the same Molx data:

li <- list(a = 1:3, b = 4:8, c = 9:10)
library(reshape2)
melt(li)
   value L1
1      1  a
2      2  a
3      3  a
4      4  b
5      5  b
6      6  b
7      7  b
8      8  b
9      9  c
10    10  c
    
05.01.2016 / 15:58