In R, as averages of spatial points over spatial mesh squares

Now I managed to solve the problem

I have a set of approximately 50 thousand points that have coordinates and one value associated with them. I would like to be able to place the points in the grid by averaging the associated value of all the points falling into the grid square. Therefore, I want to get an object that identifies each square of the grid and gives the average value inside the square of the grid.

I have data in a spatial point data frame and a spatial mesh object, if that helps.

Improving the answer: I definitely did some searching, I apologize for the initial state of the question, which I managed to solve only in my head; should not have reported this to anyone else ...

Here is an example of data that, I hope, more clearly illustrates the problem.

##make some data
longi <- runif(100,0,10)
lati <- runif(100,0,10)
value <- runif(500,20,30)

##put in data frame then change to spatial data frame
df <- data.frame("lon"=longi,"lat"=lati,"val"=value)
coordinates(df) <- c("lon","lat")
proj4string(df) <- CRS("+proj=longlat")

##create a grid that bounds the data
grd <- GridTopology(cellcentre.offset=bbox(df)[,1],
cellsize=c(1,1),cells.dim=c(11,11))
sg <- SpatialGrid(grd)

Then I hope to get an object, although a vector / frame / data list that gives me the average value in each cell / square of the grid and a way to identify which cell it is.

Decision

##convert the grid into a polygon##
polys <- as.SpatialPolygons.GridTopology(grd) 
proj4string(polys) <- CRS("+proj=longlat")

##can now use the function over to select the correct points and average them
results <- rep(0, length(polys))

for(i in 1:length(polys)) {
  results[i] = mean(df$val[which(!is.na(over(x=df,y=polys[i])))])
}

Now my question is if this is the best way to do this or is there a more efficient way?

+4
source share
1 answer

Your description is vague at best. Please try better to ask more specific answers 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.

, , - (), sp point, tapply() . , , ( ).

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)
+2

Source: https://habr.com/ru/post/1548097/


All Articles