如何从其最大值位于多边形内的栅格中提取xy坐标? [英] How to extract xy-coordinates from raster where its highest value is located within a polygon?
本文介绍了如何从其最大值位于多边形内的栅格中提取xy坐标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在多边形区域内另外获取提取的栅格最高值的坐标?
#创建栅格r<-栅格(ncol = 36,nrow = 18)r []<-runif(ncell(r))#从GridTopology创建SpatialPolygonsgrd<-GridTopology(c(-150,-50),c(40,40),c(8,3))Spol<-as(grd,"SpatialPolygons")#创建SpatialPolygonsDataFrame重心<-坐标(Spol)x<-重心[,1]y<-重心[,2]SPDF<-SpatialPolygonsDataFrame(Spol,data = data.frame(x = x,y = y,row.names = row.names(Spol))))#为每个SpatialPolygon提取栅格的最大值ext<-raster :: extract(r,SPDF,fun = max)
*示例代码取自R文档
解决方案
您可以在 extract
中使用 cellnumbers = TRUE
参数,然后使用 sapply
获取单元格编号:
ext<-raster :: extract(r,SPDF,cellnumbers = TRUE)v<-t(sapply(ext,function(i)i [which.max(i [,2]),]))#储存格值#[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
given is a raster as well as a SpatialPolygonsDataframe. In order to retrieve the highest value of the raster within the area of a polygon, raster::extract can be used. It works fine.
How to get additionally the coordinates of the extracted highest value of the raster within the area of a polygon?
# create raster
r <- raster(ncol=36, nrow=18)
r[] <- runif(ncell(r))
# create SpatialPolygons from GridTopology
grd <- GridTopology(c(-150, -50), c(40, 40), c(8, 3))
Spol <- as(grd, "SpatialPolygons")
# create SpatialPolygonsDataFrame
centroids <- coordinates(Spol)
x <- centroids[,1]
y <- centroids[,2]
SPDF <- SpatialPolygonsDataFrame(Spol, data=data.frame(x=x, y=y, row.names=row.names(Spol)))
# extract max value of raster for each SpatialPolygon
ext <- raster::extract(r, SPDF, fun=max)
*example code is taken from R-documentation
解决方案
You can use the cellnumbers=TRUE
argument in extract
, followed by a sapply
to get the cell number:
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
To get the coordinates:
xyFromCell(r, v[,1])
# x y
# [1,] -135 35
# [2,] -105 35
# [3,] -85 45
# [4,] -25 25
# [5,] -5 25
这篇关于如何从其最大值位于多边形内的栅格中提取xy坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文