R 如何将具有非唯一行名的列表转换为具有唯一行名的(嵌套)列表?
我有一个很长的列表e2i,它将行名“映射”到值,并且有重复的行名:R 如何将具有非唯一行名的列表转换为具有唯一行名的(嵌套)列表?,r,R,我有一个很长的列表e2i,它将行名“映射”到值,并且有重复的行名: > head(e2i) $`679594` [1] "IPR019956" $`679594` [1] "IPR019954" $`679594` [1] "IPR019955" $`679594` [1] "IPR000626" $`682397` [1] "IPR019956" $`682397` [1] "IPR019954" 我需要将其转换为一个具有唯一行名的列表,其中每个命名元素都是一个(命名或未命名
> head(e2i)
$`679594`
[1] "IPR019956"
$`679594`
[1] "IPR019954"
$`679594`
[1] "IPR019955"
$`679594`
[1] "IPR000626"
$`682397`
[1] "IPR019956"
$`682397`
[1] "IPR019954"
我需要将其转换为一个具有唯一行名的列表,其中每个命名元素都是一个(命名或未命名)值的列表:
我相信有一个简短而优雅的解决方案
至于长而丑陋的解决方案-我想我可以通过这样的循环来实现:
mytest = function(e2i) {
result = list()
for (e in names(e2i)) {
# iterate all rownames, including duplicates
if (e %in% names(result)) {
# convert existing element to a list (if not already a list),
# then append new value e2i[[e]] to that nested list
}
else {
# just add the value to the result
result = c(result, e2i[[e]])
}
}
return(result)
}
最初数据在矩阵中,对于上面的循环解决方案草案,我将使用它作为输入:
> head(entrez2interpro_matrix)
EntrezGene.ID Interpro.ID
1 679594 IPR019956
2 679594 IPR019954
3 679594 IPR019955
4 679594 IPR000626
5 682397 IPR019956
6 682397 IPR019954
你看过包裹了吗
或者只需使用unstack()
:
谢谢,我使用了unstack()-一个适合我需要的向量列表以及一个列表列表。
> head(entrez2interpro_matrix)
EntrezGene.ID Interpro.ID
1 679594 IPR019956
2 679594 IPR019954
3 679594 IPR019955
4 679594 IPR000626
5 682397 IPR019956
6 682397 IPR019954
> d
EntrezGene.ID Interpro.ID
1 679594 IPR019956
2 679594 IPR019954
3 679594 IPR019955
4 679594 IPR000626
5 682397 IPR019956
6 682397 IPR019954
> unstack(d, Interpro.ID ~ EntrezGene.ID)
$`679594`
[1] "IPR019956" "IPR019954" "IPR019955" "IPR000626"
$`682397`
[1] "IPR019956" "IPR019954"