Home > Blockchain >  Overriding error in a loop and asking the loop to assign a value of zero instead
Overriding error in a loop and asking the loop to assign a value of zero instead

Time:12-06

I am calculating the percent overlap between pairs of animal home ranges, which are represented as sldf objects (Spatial Lines Data Frame). To do so, I created an empty vector, and then made a loop calculating the home ranges and the percent overlap before filling the empty vector with those overlap values.

Here is the last part of my loop:

  #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
  

When there is no overlap between my two polygons, my loop stops and I get an error. This error is associated with the line of code

intersections<-gIntersection(sldf, sldf2)

The error is

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

My issue is that some of my overlaps will necessarily be zero. This is not something I can change as it is part of my data.

I'm trying to find a way for my loop to override this error and place the value zero in my vector when this occurs. So far, I have tried the following as suggested in comments:

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

However, this causes the next line of code (overlap<-gArea(intersections)/base_area) to crash because the function gArea is meant to handle spatial objects only, not numeric objects like zero. It returns the warning Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘is.projected’ for signature ‘"numeric"’.

I've also tried using the dplyr function if_else and purrr.possibly, but no luck. I get the same error. Any suggestions?

CodePudding user response:

You can use try from the BBmisc library with is_null, as follows:

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

Hope it helps.

  • Related