lundi 2 août 2021

Converting empty list() into NULL in R?

I am updating a function in R which I did not wrote myself and having trouble working/understanding how to deal with if()

My problem is xpathApply()is returning a empty list list() and not a NULL object, so if(is.null()) is not returning the taxon$name, what causes the next line of code to crash. Is there a way to turn this empty list into a NULL object, or any other solution that can be used with if()? Since I am running this in a for in loop with many iterations and most of the links will not return empty lists.

Here is some reproducible code:

library('XML')
library('plyr')
library('httr')


name<- c("Hemigraphis reptans")
URL<- c("https://naturalhistory2.si.edu/botany/marquesasflora/results.cfm?genus=Hemigraphis&specificepithet=reptans&rank=&epithet1=")
taxon<- data.frame(name,URL, stringsAsFactors=FALSE)


query_page = htmlTreeParse(rawToChar(GET(taxon$URL)$content), useInternalNodes = T)
  
name_accept = xpathApply(query_page, path = "//*//div[@id = 'mainArticle']//*//b", xmlValue)
  if(is.null(name_accept)){
    return(data.frame(Species = taxon$name))
  }
name_accept = as.data.frame(matrix(unlist(name_accept), ncol = 3, byrow = T), stringsAsFactors = F)

Thanks for the help.

Aucun commentaire:

Enregistrer un commentaire