3

I have a named list that looks like this:

> head(pathways)
$<NA>
NULL
$`2`
[1] "hsa04610"
$`9`
[1] "hsa00232" "hsa00983" "hsa01100"
$`10`
[1] "hsa00232" "hsa00983" "hsa01100"
$<NA>
NULL
$<NA>
NULL

To describe it more formerly. The name of each list is an id number, and the entries of each element of the character vector that are elements of the list is another id number. I can filter out the $<NA> entries easily with is.na(), but then I want to change the rest so it would look like:

id   another_id
2    hsa04610   
9    hsa00232   
9    hsa00983   
9    hsa01100   
10   hsa00232  
10   hsa00983
10   hsa01100


> dput(test)
structure(list(`NA` = NULL, `2` = "hsa04610", `9` = c("hsa00232", 
"hsa00983", "hsa01100"), `10` = c("hsa00232", "hsa00983", "hsa01100"
), `NA` = NULL, `NA` = NULL), .Names = c(NA, "2", "9", "10", 
NA, NA))

Any ideas?

Davy Kavanagh
  • 4,809
  • 9
  • 35
  • 50
  • 1
    It would help if you were to post the output from `dput(head(pathways))`. – IRTFM Jun 28 '12 at 12:34
  • 1
    So while waiting for answers, which wasn't long (cheers, btw) I continued to google and found this post http://stackoverflow.com/questions/10432993/named-list-to-from-data-frame which basically says I can use stack(pathways). Will this work? It seems to simple? – Davy Kavanagh Jun 28 '12 at 12:49
  • It did work on your test object. (without even removing the NA entries ...to my surprise.) Kudos on the googling, BTW. – IRTFM Jun 28 '12 at 13:01
  • Slightly embarrassed that I found immediately after posting the question. – Davy Kavanagh Jun 28 '12 at 13:10

3 Answers3

6

So I found another answer that seems to work.

stack(pathways)

This seems too easy, but oh well.

Davy Kavanagh
  • 4,809
  • 9
  • 35
  • 50
2

So if you have list l (after removing NA's), then:

another_id <- unlist(l)
id <- rep(names(l), unlist(lapply(l, length)))
data.frame(id, another_id, row.names=NULL)

will give the result.

danas.zuokas
  • 4,551
  • 4
  • 29
  • 39
2
#sample data
pathways <- list(`1` = letters[1:3], `2` = LETTERS[4:5], `3` = 6:9, `4` = NULL)

#a solution
n <- vapply(pathways, length, integer(1))
id <- rep.int(names(pathways), n)
another_id <- unlist(pathways, use.names = FALSE)
data.frame(id = id, another_id = another_id)
Richie Cotton
  • 118,240
  • 47
  • 247
  • 360