r语言 - 覆盖循环中的错误,并要求循环赋值为0



我正在计算动物活动范围对之间的重叠百分比,它们表示为sldf对象(空间线数据帧)。为此,我创建了一个空向量,然后循环计算主范围和重叠百分比,然后用这些重叠值填充空向量。

这是我的循环的最后一部分:

#Calculate percent overlap  
base_area <- gArea(sldf)
intersections<-gIntersection(sldf, sldf2)
overlap<-gArea(intersections)/base_area

Overlap[i]<-overlap #Place overlap value in empty vector

当我的两个多边形之间没有重叠时,我的循环停止并得到一个错误。此错误与

代码行相关联
intersections<-gIntersection(sldf, sldf2)

错误是

Error in (function (classes, fdef, mtable)  : 
unable to find an inherited method for function ‘is.projected’ for signature ‘"NULL"’

我的问题是我的一些重叠部分必然是零。这不是我可以改变的东西,因为它是我数据的一部分。

我正试图找到一种方法让我的循环覆盖此错误,并在发生这种情况时将值零放在我的向量中。到目前为止,我已经按照注释中的建议尝试了以下操作:

intersections <- try(gIntersection(sldf, sldf2), silent=T)
if(is_null(intersections))
intersections <- 0

然而,这会导致下一行代码(overlap<-gArea(intersections)/base_area)崩溃,因为函数gArea只用于处理空间对象,而不是像0这样的数字对象。它返回警告Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘is.projected’ for signature ‘"numeric"’

我还尝试使用dplyr函数if_else和purrr。可能吧,但运气不好。我得到了同样的错误。有什么建议吗?

您可以将BBmisc库中的tryis_null一起使用,如下所示:

intersections <- try(gIntersection(sldf, sldf2), silent=T)
if(is_null(intersections)){
intersections <- 0
overlap <- 0
}
else
overlap <- gArea(intersections)/base_area

希望有帮助。

最新更新