In R, how to average spatial points data over spatial grid squares

倾然丶 夕夏残阳落幕 提交于 2019-12-05 10:55:09

Your description is vague at best. Please try to ask more specific answers preferably, with code illustrating what you have already tried. Averaging a single value in your point data or a single raster cell makes absolutely no sense.

The best guess at an answer I can provide is to use raster extract() to assign the raster values to a sp point object and then use tapply() to aggregate the values to your grouping values in the points. You can use the coordinates of the points to identify cell location or alternately, the cellnumbers returned from extract (per below example).

require(raster)
require(sp)

# Create example data
r <- raster(ncol=500, nrow=500)
  r[] <- runif(ncell(r))
    pts <- sampleRandom(r, 100, sp=TRUE)  

# Add a grouping value to points 
pts@data <- data.frame(ID=rownames(pts@data), group=c( rep(1,25),rep(2,25),
                       rep(3,25),rep(4,25)) )          

# Extract raster values and add to @data slot dataframe. Note, the "cells" 
#   attribute indicates the cell index in the raster. 
pts@data <- data.frame(pts@data, extract(r, pts, cellnumbers=TRUE))
  head(pts@data)

# Use tapply to cal group means  
tapply(pts@data$layer, pts@data$group, FUN=mean)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!