Wednesday, November 6, 2019

Simple wrapper function to check a "phylo" object

Recently the following inquiry was sent to the R-sig-phylo email list:

“I am working with the phylo object from the ape package in my own package in which I am manipulating the trees. I would like to check that I have successfully created a valid ape object, but the checkValidPhylo function appears to be solely interactive - it prints out a display, and always returns NULL. Is there a function in the ape package (or can there be?) that would do the checks, but return the results in a way that I can then process in my function? (e.g. return a vector of each of the checks as TRUE/FALSE) (And I don't want anything printed out, since I don't want that output to be printed for users of my function).”

I suggested the following solution (which turned out to be satisfactory).

This simple function captures the printed output of checkValidPhylo, which can find MODERATE, FATAL, or no errors. If no error is detected, the function returns a 0. If at least one FATAL error is detected, it returns a 2, otherwise (if only MODERATE errors are found), it returns a 1:

chk.phylo<-function(x){
    object<-capture.output(checkValidPhylo(x))
    if(length(grep("FATAL",object))>0) return(2)
    else if(length(grep("MODERATE",object))>0) return(1)
    else return(0)
}

Let's try it out:

library(ape)
t1<-rtree(n=10) ## good tree
chk.phylo(t1)
## [1] 0
t2<-t1
t2$Nnode<-9.5 ## tree has non-integer Nnode
## should cause a MODERATE error
chk.phylo(t2)
## [1] 1
t3<-t1
t3$edge<-t3$edge[-4,] ## tree is missing an
## edge, should cause a FATAL error
chk.phylo(t3)
## [1] 2

That's it.

No comments:

Post a Comment

Note: due to the very large amount of spam, all comments are now automatically submitted for moderation.