您可以使用cellnumbers=TRUE
论证中extract
。使用“terra”你可以做到
library(terra)
r <- rast(system.file("ex/elev.tif", package="terra"))
v <- vect(system.file("ex/lux.shp", package="terra"))
e <- terra::extract(r, v, xy=TRUE, ID=TRUE)
m <- merge(aggregate(elevation~ID, max, data=e), e)
head(m)
# ID elevation x y
#1 1 547 6.020833 50.17917
#2 10 432 5.987500 49.46250
#3 11 427 6.204167 49.67917
#4 12 413 6.154167 49.77083
#5 2 514 6.087500 49.97917
#6 3 517 5.879167 49.84583
完成最后一步的另一种方法
b <- by(e, e$ID, FUN=function(d) d[which.max(d$elevation),])
b <- do.call(rbind, b)
head(b)
# ID elevation x y
#1 1 547 6.020833 50.17917
#2 2 514 6.087500 49.97917
#3 3 517 5.879167 49.84583
#4 4 520 6.112500 49.97917
#5 5 511 5.937500 49.87917
#6 6 403 6.270833 49.83750
这里有您的示例数据和旧包:
ext <- raster::extract(r, SPDF, cellnumbers=TRUE)
v <- t(sapply(ext, function(i) i[which.max(i[,2]), ] ))
# cell value
# [1,] 185 0.9303460
# [2,] 188 0.9821190
# [3,] 154 0.9926290
# [4,] 232 0.8907819
# [5,] 234 0.9998510
获取坐标:
xyFromCell(r, v[,1])
# x y
# [1,] -135 35
# [2,] -105 35
# [3,] -85 45
# [4,] -25 25
# [5,] -5 25