我正在使用if-else-formulation计算几个shapefile之间的重叠百分比,从而导致常见错误消息:subscript out of bounds
这是我的代码:
## load libraries
library(raster)
library(rgeos)
setwd("...")
可以here访问文件。
加载文件:
# 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公式?
非常感谢您的帮助。非常感谢!