Jojo
Jojo

Reputation: 5201

Calculating mean values per grid-cell of data with associated coordinates

I have a raster file called gridmap, projected in UTM, of class: SpatialGridDataFrame which looks like this:

Object of class SpatialGridDataFrame
Coordinates:
        min    max
[1,]  415.0  545.5
[2,] 6371.5 6493.0
Is projected: TRUE 
proj4string :
[+proj=utm +ellps=WGS84 +datum=WGS84 +zone=30 +units=km +towgs84=0,0,0]
Grid attributes:
  cellcentre.offset cellsize cells.dim
1            415.25      0.5       261
2           6371.75      0.5       243
Data attributes:
     values     
 Min.   :    1  
 1st Qu.:15856  
 Median :31712  
 Mean   :31712  
 3rd Qu.:47568  
 Max.   :63423  

I also have a data frame which has coordinates and values (V1) associated with those coordinates. There can be multiple values for certain coordinates.

DF <- data.frame(
    Lat = c(6384.705, 6384.701, 6384.698, 6384.698, 6384.691, 6384.687)
    Lon = c(439.7384, 439.7385, 439.7386, 439.7387, 439.7389, 439.7390)
    V1 = c(34, 0.006, 76, 34, 777, 0.0000348)
)

What I would like to do is take the mean value of V1 for each GRID-CELL in my raster, not for each discrete coordinate in the data frame, and create a data frame which has The grid cell value, Raster Coordinate Value and mean V1. I can figure out how to overlay the locations onto the gridmap to get the grid-cell IDs for each observation using this code:

coords <- data.frame(cbind(DF$Lon, DF$Lat))   
coords <- SpatialPointsDataFrame(coords, data = data.frame(DF), proj4string = CRS(projUTM))
siteSpo <- over(x=coords, y=gridmap) 
DF$siteID <- siteSpo$values  

But I can't figure out the next step of averaging each value for each individual grid-cell ID and creating a new SpatialGridDataFrame which has all the mean grid-cell values, including the 0's where I have no data.

Upvotes: 0

Views: 2553

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47061

I would first make a RasterLayer object

library(raster)
#r <- raster("gridmap file")

As we don't have your file, here is an example (you can also do r <- raster(gridmap)).

r <- raster(ncol=261, nrow=243, xmn=415, xmx=545.5, ymn=6371.5, ymx=6493.0)
values(r) <- 1:ncell(r)

Now:

df <- data.frame(
    y = c(6372, 6378, 6384, 6384, 6485, 6487),
    x = c(419, 429, 439, 439, 539, 500),
    V1 = c(34, 0.006, 76, 34, 777, 0.0000348)
)
df <- aggregate(df[, 'V1', drop=FALSE], df[,2:1], mean)
df$grid <- extract(r, df[,c('x', 'y')])

df
#    x    y       V1  grid
#1 419 6372 3.40e+01 63171
#2 429 6378 6.00e-03 60059
#3 439 6384 5.50e+01 56947
#4 539 6485 7.77e+02  4425
#5 500 6487 3.48e-05  3303

Upvotes: 1

Related Questions