简体   繁体   中英

Recursive access to elements in list of lists in R

I'm using the Annotation package of R to get GO terms related to certain genes. Using getGOParents(term) function the result is:

> x = getGOParents("GO:0035556")

$`GO:0035556`
$`GO:0035556`$Ontology
[1] "BP"

$`GO:0035556`$Parents
    is_a 
"GO:0007165" 

The structure of the list is:

dput(x)
structure(list(`GO:0035556` = structure(list(Ontology = "BP", 
Parents = structure("GO:0007165", .Names = "is_a")), .Names = c("Ontology", 
"Parents"))), .Names = "GO:0035556")

I need to access the "last" term of the list, I did it in a really silly way:

y=x[1]
z=y[[1]]
w=z[[2]]
s=w[[1]]

Is there a way to programmatically access it?

You can use rapply which is a recursive version of lapply. Here I apply the identity function on the terminal nodes of your list.

 rapply(x,f=I)
GO:0035556.Ontology GO:0035556.Parents.is_a 
               "BP"            "GO:0007165"

Or to access one by one

rapply(x,f=I)[2] 
GO:0035556.Parents.is_a 
       "GO:0007165" 

Note that you could have condensed your method to

x[[1]][[2]][[1]]

One thing you could do is remove the list structure by using unlist

unlist(x)
#GO:0035556.Ontology GO:0035556.Parents.is_a 
#               "BP"            "GO:0007165" 

and you can access those individually through indexing

> unlist(x)[1]
GO:0035556.Ontology 
               "BP" 
> unlist(x)[2]
GO:0035556.Parents.is_a 
           "GO:0007165" 

I used this function for it:

getParent <- function(x){
    parent = NA
    if(exists(x,revmap(GOBPCHILDREN))){
        parents = get(x,revmap(GOBPCHILDREN))
        parent = tail(parents, n=1)
    }
    if(!is.na(parent)){
        return(parent)
    }
    return(NA)
}

But I didn't want the highest parents, because this one is always the same. So I changed the function to:

getParent <- function(x){
    parent = NA
    if(exists(x,revmap(GOBPCHILDREN))){
        parents = get(x,revmap(GOBPCHILDREN))
        parent = tail(parents, n=4)[1] ##change the 4 to which level you want
    }
    if(!is.na(parent)){
        return(parent)
    }
    return(NA)
}

A nice visualisation tool for the GO terms is GOrilla: http://cbl-gorilla.cs.technion.ac.il/

I hope u can do something with this information

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM