I have list where the elementnames are ID-tags and contains a vector with numeric values. These are of unequal(!) length.
I want to transform it to a data frame where I have the ID in one column and the numeric values in another column. E.g.:
$`1`
[1] 1 2
$`2`
[1] 1 2 3
$`3`
[1] 1
To:
ID Obs
1 1
1 2
2 1
2 2
2 3
3 1
Here is one way:
## your list
ll <- list("1" = 1:2, "2" = 1:3, "3" = 1:2)
## convert to data.frame
dl <- data.frame(ID = rep(names(ll), sapply(ll, length)),
Obs = unlist(ll))
This gives:
> dl
ID Obs
11 1 1
12 1 2
21 2 1
22 2 2
23 2 3
31 3 1
32 3 2
The first line in the data.frame()
call is just some code to repeat the names()
of the list the required number of times. The second line just unlists the list converting it into a vector.
Use reshape2
and melt
which has a method melt.list
.list <- list(`1` = 1:2, `2` = 1:3, `3` = 1:2)
library(reshape2)
melt(.list)
## value L1
## 1 1 1
## 2 2 1
## 3 1 2
## 4 2 2
## 5 3 2
## 6 1 3
## 7 2 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With