开发者

R combine list to specical format of table

开发者 https://www.devze.com 2023-03-07 10:24 出处:网络
I have a list of comprising of sub-lists with different numbers of entries, as follows: x <- list( c(\"a1\", \"a2\", \"a3\", \"a4\", \"a5\", \"a6\", \"a7\"),

I have a list of comprising of sub-lists with different numbers of entries, as follows:

x <- list(
  c("a1", "a2", "a3", "a4", "a5", "a6", "a7"),
  c("b1","b2","b3","b4"),
  c("c1","c2","c3"),
  c("d1")
)

I want to convert this file to a dataframe with three columns (1st column is sequence of the sub-list, i.e. 1 to 4: 2nd column is the entries; the 3rd stands for my stop code, so, I used 1 for every lines, the final results is as follows:

1  a1  1
1  a2  1
1  a3  1
1  a4  1
1  a5  1
1  a6  1
1  a7  1
2  b1  1
2  b2  1
2  b3  1
2  b4  1
3  c1  1
3  c2  1
3  c3  1
4  d1  1

I tried to use cbind, however, it seems to me only works for sub-list with same number of entries. Are there any smarter way of doing t开发者_开发百科his?


here is an example:

data.frame(
  x=rep(1:length(x), sapply(x, length)),
  y=unlist(x),
  z=1
)


library(reshape2)

x <- melt(x) ## Done...

## Trivial...
x$stop <- 1
x <- x[c(2,1,3)]


One option is to use the split, apply, combine functionality in package plyr. In this case you need ldply which will take a list and combine the elements into data.frame:

library(plyr)
ldply(seq_along(x), function(i)data.frame(n=i, x=x[[i]], stop=1))

   n  x stop
1  1 a1    1
2  1 a2    1
3  1 a3    1
4  1 a4    1
5  1 a5    1
6  1 a6    1
7  1 a7    1
8  2 b1    1
9  2 b2    1
10 2 b3    1
11 2 b4    1
12 3 c1    1
13 3 c2    1
14 3 c3    1
15 4 d1    1
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号