calculate mean for each cell in grid in R

195 Views Asked by At

Possible Duplicate:
Sliding window function in R

This might be a silly question, but I couldn't find an answer so far. I have a data frame like this:

df <- data.frame(lat = (-10: 10),
                 lon = (-10: 10),
                 A = runif(21, 1 ,10),
                 B = runif(21, 20 ,30))

where lat and lon are geographic coordinates, and A and B are two continuos variables. What I would like to do, is to create a 5 by 5 grid and calculate the mean value of A and B within each cell of the grid. Here is the approach I'm trying but with no success...

library(raster)
library(maptools)

coordinates(df) <- ~ lat + lon
rast <- raster(ncol = 5, nrow = 5)
extent(rast) <- extent(df)
rasterize(df, rast, df$A, fun = mean)
0

There are 0 best solutions below