如何从多边形数据中提取栅格值,然后合并到空间数据框中? [英] How do I extract raster values from polygon data then join into spatial data frame?

查看:213
本文介绍了如何从多边形数据中提取栅格值,然后合并到空间数据框中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将多边形数据和栅格数据合并到一个数据框中,以便随后在R中使用randomForests包.
这涉及首先提取每个多边形的平均栅格值.

I would like to merge polygon data and raster data into one dataframe for purposes of then using randomForests package in R.
This involves first extracting the mean raster value per polygon.

到目前为止,我有以下内容:

So far, I have the following:

#load libraries
library(raster)
library(rgdal)
library(sp)
library(maptools)

#import raster data 
r <- raster("myRasterdata.tif")

#import polygon data 
p <- readShapePoly("myPolydata.shp")

#extract mean raster value for each polygon
ExtractMyData <- extract(r, p, small=TRUE, fun=mean, na.rm=TRUE, df=FALSE,  nl=1, sp=TRUE)
# note I have also tried this with df=TRUE and sp=FALSE

输出是一个矩阵,我可以将其写入数据框.但是它没有空间坐标或原始的多边形ID,所以我不知道如何将输出连接到同一数据库中.我以为sp = TRUE参数可以做到这一点,但它似乎不起作用.

The output is a matrix, which I can write to a dataframe. But it does not have the spatial coordinates or the original polygon IDs, so I don't know how to join the output into the same database.I thought the sp=TRUE argument would do this, but it doesn't seem to work.

请注意,出于RandomForests的目的,我实际上将不得不将多边形转换为点(使用质心方法?),因此我可以猜到我真正想要的是将平均栅格值加入到点而不是多边形中.

Note that I will actually have to convert the polygons to points (using a centroid method?) for purposes of RandomForests so I could guess what I really want is to join the mean raster values joined to points, not polygons.

任何建议将不胜感激.谢谢!!

Any suggestions would be greatly appreciated. Thank you!!

推荐答案

这有效:

library(raster)
library(sp)
library(maptools)


#import polygon data 
data(wrld_simpl)
p <- wrld_simpl

#create raster data 
r <- raster(extent(p))
r[] <- seq_len(ncell(r))


## this does it directly, adding columns "names(r)" to "p" 
p <- extract(brick(r, r * 2), p, fun = mean, na.rm = TRUE, sp = TRUE)

您也可以手动进行操作,了解如何使用聚合函数提取单个列向量:

You can also do it more manually, see how extract with an aggregating function gives a single column vector:

p$ExtractData <- extract(r, p, fun = mean, na.rm = TRUE)

或者您可以像这样逐列处理多层栅格:

Or you could work on a multi-layer raster, column by column like this:

b <- brick(r, r * 2)
extr <- extract(b, p, fun = mean, na.rm = TRUE)
for (i in seq_len(ncol(extr))) p[[colnames(extr)[i]]] <- extr[,i]

这篇关于如何从多边形数据中提取栅格值,然后合并到空间数据框中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆