How do I extract raster values from polygon data then join into spatial data frame?

牧云@^-^@ 提交于 2019-12-04 08:43:38

This works:

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]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!