A solution using base functions
List <- list('1'=c(1,2), '2'= c(1,2,3), '3'=1)
x <- unlist(List) # as suggested by Gavin Simpson
data.frame(ID=substr(names(x),1,1), Obs=x)
ID Obs
11 1 1
12 1 2
21 2 1
22 2 2
23 2 3
3 3 1
If you want the rownames
to be 1,2,3,4,5,6 the try this (using setNames
):
data.frame(ID=substr(names(x),1,1), Obs=setNames(x, NULL))
ID Obs
1 1 1
2 1 2
3 2 1
4 2 2
5 2 3
6 3 1
This solution is valid only if all names have the same length, otherwise it'll fail, and it'd be better using Gavin's solution. See for example:
List2 <- list('week1'=c(1,2), 'week2'= c(1,2,3), 'week3'=1)
x <- unlist(List2)
data.frame(ID=substr(names(x),1,nchar(names(x)[1])-1), Obs=setNames(x, NULL))
ID Obs
1 week1 1
2 week1 2
3 week2 1
4 week2 2
5 week2 3
6 week3 1
> system.time(melt(X))
user system elapsed
3.12 0.11 3.24
> system.time(data.frame(ID = rep(names(X), sapply(X, length)), Obs = unlist(X)))
user system elapsed
0.08 0.00 0.07
– ego_ Sep 28 '12 at 12:18