我有一个清单
mylist<-list( "[3] C(+57.02)", c("[11] C(+57.02)", "[16] C(+57.02)"), "[3] C(+57.02)",c ("[5] M(+15.99)", "[6] M(+15.99)"))
我想得到一个这样的表,其中名称是对象列表编号。
1 2 2 3
"[3] C(+57.02)" , "[11] C(+57.02)", "[16] C(+57.02)", "[3] C(+57.02)",
4 4
"[5] M(+15.99)", "[6] M(+15.99)"
我试图这样做但不完全是我想要的。
table(unlist(mylist))
[11] C(+57.02) [16] C(+57.02) [3] C(+57.02) [5] M(+15.99) [6] M(+15.99)
1 1 2 1 1
答案 0 :(得分:2)
您可以使用rep
+ seq_along
+ lengths
+ setNames
:
setNames(unlist(mylist), rep(seq_along(mylist), lengths(mylist)))
## 1 2 2 3 4 4
## "[3] C(+57.02)" "[11] C(+57.02)" "[16] C(+57.02)" "[3] C(+57.02)" "[5] M(+15.99)" "[6] M(+15.99)"
更好的演示可能是使用stack
:
stack(setNames(mylist, seq_along(mylist)))
## values ind
## 1 [3] C(+57.02) 1
## 2 [11] C(+57.02) 2
## 3 [16] C(+57.02) 2
## 4 [3] C(+57.02) 3
## 5 [5] M(+15.99) 4
## 6 [6] M(+15.99) 4
答案 1 :(得分:1)
我使用了一个命名的字符向量。不知道为什么你想要table
。
数据:
mylist<-list( "[3] C(+57.02)", c("[11] C(+57.02)", "[16] C(+57.02)"), "[3] C(+57.02)",c ("[5] M(+15.99)", "[6] M(+15.99)"))
代码:
v <- unlist(mylist)
names(v) <- rapply(mylist,length) %>% rep(seq_along(mylist),.)
输出:
> v
1 2 2 3 4 4
"[3] C(+57.02)" "[11] C(+57.02)" "[16] C(+57.02)" "[3] C(+57.02)" "[5] M(+15.99)" "[6] M(+15.99)"
>