【问题标题】:Converting empty list() into NULL in R?在R中将空列表()转换为NULL?
【发布时间】:2021-10-07 22:31:04
【问题描述】:

我正在更新 R 中的一个函数,该函数不是我自己编写的,并且在工作/理解如何处理 if() 时遇到了麻烦

我的问题是xpathApply()返回一个空列表list()而不是NULL对象,所以if(is.null())没有返回taxon$name,是什么导致下一行代码崩溃。有没有办法把这个空列表变成一个 NULL 对象,或者任何其他可以与 if() 一起使用的解决方案?由于我在 for in 循环中运行此程序,并进行了多次迭代,并且大多数链接不会返回空列表。

这是一些可重现的代码:

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)

感谢您的帮助。

【问题讨论】:

  • 找不到记录会不会有问题?
  • 仅将list() 更改为NULL 将无济于事,因为您无法将其转换为矩阵(最后一行)。如果该物种被接受,很高兴看到它应该如何表现。可能以某种方式重写你的代码,你问if(length(name_accept) == 0) ...。空列表的长度为0,NULL的长度也是。
  • @nachti 谢谢,这确实有效。我只是将if(is.null()) 更改为建议的if(length(name_accept) == 0)。您可以将其发布为答案吗?

标签: r xml for-loop if-statement


【解决方案1】:

将您的 if 条件从 if(is.null(name_accept)) 更改为 if(length(name_accept) == 0) 可能会解决问题。空列表的长度为0,也为NULL。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-13
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2022-01-18
    • 1970-01-01
    • 2020-07-20
    • 2022-06-11
    相关资源
    最近更新 更多