Индекс вне границ в цикле if-else - PullRequest
0 голосов
/ 18 февраля 2019

Я рассчитываю процент перекрытия между несколькими шейп-файлами с помощью формулы if-else, приводящей к общему сообщению об ошибке: subscript out of bounds

Вот мой код:

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

К файлам можно получить доступ здесь .

Загрузите файлы:

# 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))
    }
  }
}

Это приводит к появлению этого сообщения об ошибке:

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

Тем не менее, много занимает в матрице вывода:

# take a look at output matrix
overlap

Показывает это:

> 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

Это результат, который я хочу, но расчет не завершен.Из команд print я знаю, что вычисление пересечения файлов TypeA2 и TypeB3 было последней операцией до возникновения ошибки.Как мой код можно изменить, чтобы избежать этой ошибки?Я знаю о некоторых решениях, таких как this , но изо всех сил пытаюсь приспособить это к моему случаю.Как можно изменить формулировку if-else?

Ваша помощь высоко ценится.Большое спасибо!

...