lundi 18 février 2019

Subscript out of bounds in if-else-loop

I am calculating the percentage of overlap between several shapefiles with an if-else-formulation resulting in a common error message: subscript out of bounds

Here is my code:

## load libraries
library(raster)
library(rgeos)
setwd("...")

The files can be accessed here.

Load the files:

# Type A
TypeA1 <- shapefile("TypeA1")
TypeA2 <- shapefile("TypeA2")
TypeA3 <- shapefile("TypeA3")
# Type B
TypeB1 <- shapefile("TypeB1")
TypeB2 <- shapefile("TypeB2")
TypeB3 <- shapefile("TypeB3")

# create lists of all Type A / Type B files
Alist <- c("TypeA1", "TypeA2", "TypeA3")
Blist <- c("TypeB1", "TypeB2", "TypeB3")

# lapply
Afiles <- lapply(Alist, shapefile)
Bfiles <- lapply(Blist, shapefile)

### compare individual file combinations by percentage of overlap
# Type A - Type B
# construct output matrix based on file lists
n <- length(Afiles)
m <- length(Bfiles)
overlap <- matrix(0, nrow=n, ncol=m)
rownames(overlap) <- Alist
colnames(overlap) <- Blist
# set indices
for (i in 1:n) {
  area(Afiles[[i]])
}
for (j in 1:m) {
  area(Bfiles[[j]])
}
# calculate percentage of overlap for all Type A files with all Type B files
overlap_perc <- for (i in 1:n) {
  for (j in 1:m) {
    intersection <- gIntersection(gBuffer(Afiles[[i]],width=0), gBuffer(Bfiles[[j]],width=0))
    print(paste0("calculate intersection of ", Alist[[i]], " and ", Blist[[j]]))
    if (!is.null(intersection)) {
      aintersection <- area(intersection)
      overlap[i,j] <- round((aintersection / area(Afiles[[i]]))*100, 2)
      print(paste0("calculate overlap between ", Alist[[i]], "-", Blist[[j]], "-intersection and ", Alist[[i]]))
    } else {
      intersection <- gIntersection(gBuffer(Afiles[[i]],width=0), gBuffer(Bfiles[[j+1]],width=0))
    }
  }
}

This results in this error message:

Error in Bfiles[[j + 1]] : subscript out of bounds

Nevertheless, taking a lot at the output matrix:

# take a look at output matrix
overlap

Shows this:

> overlap
       TypeB1 TypeB2 TypeB3
TypeA1   4.66   0.00  59.68
TypeA2   0.00  55.81   0.00
TypeA3   0.00   0.00   0.00

That is the result I want but the calculation is incomplete. From the print commands I know that the calculation of the intersection of the files TypeA2 and TypeB3 was the last operation before the error occured. How can my code be adjusted to avoid this error? I am aware of some solutions like this but struggle to adapt this to my case. How can the if-else-formulation be modified?

Your help is highly appreciated. Thanks a lot!

Aucun commentaire:

Enregistrer un commentaire