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

Asked

Viewed 108 times

7

Considering a list x composed of nvectors. To illustrate the problem I thought it had 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 on this list on data.frame 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

3 answers

5


There is a function on the base that does just that, called stack. The hardest part of using it is remembering the name, because it is very unusual (I spent 10 minutes searching until I found...):

> 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
  • 1

    good! for sure this is the best way to do!

  • Very good!!! Thank you, helped me a lot.

3

You can also use the function melt package reshape2.

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

3

Another way to do this is this:

> 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 assign it the name of a column, it uses the list identifier as the id of each row.

  • It worked perfectly! Thanks for the strength.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.