2

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)
Community
  • 1
  • 1
matteo
  • 645
  • 3
  • 10
  • 18
  • 1
    You're looking for the `focal()` function in the **raster** package: http://stackoverflow.com/questions/9931706/sliding-window-function-in-r/9933326#9933326 – Josh O'Brien Jan 16 '13 at 15:38
  • Thanks Josh, thats should do. – matteo Jan 16 '13 at 15:58
  • 1
    We should either close this as a duplicate or matteo should finish this with an answer based on his new knowledge. Everyone should go to the link and upvote Josh's useful answer while they are at it. – IRTFM Jan 16 '13 at 17:54
  • ok DWin, can be closed, I'm happy with the solution pointed out by Josh, and I've up-voted his other post. – matteo Jan 16 '13 at 18:53

0 Answers0