I have a long list e2i, which "maps" rownames to values, and has duplicate rownames:
> head(e2i)
$`679594`
[1] "IPR019956"
$`679594`
[1] "IPR019954"
$`679594`
[1] "IPR019955"
$`679594`
[1] "IPR000626"
$`682397`
[1] "IPR019956"
$`682397`
[1] "IPR019954"
I need to convert it into a list with unique rownames, where each named element would be a list of (either named or unnamed) values:
> str(mylist)
List of 2
$ 679594:List of 3
..$ : chr "IPR019956"
..$ : chr "IPR019954"
..$ : chr "IPR019955"
$ 682397:List of 2
..$ : chr "IPR019956"
..$ : chr "IPR019954"
I believe there's a short and elegant solution.
As for long and ugly solution - I think I could do that with a loop like this:
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)
}
Initially data was in a matrix, and for my loop solution draft above I'd use it as input:
> 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