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.
longi <- runif(100,0,10)
lati <- runif(100,0,10)
value <- runif(500,20,30)
df <- data.frame("lon"=longi,"lat"=lati,"val"=value)
coordinates(df) <- c("lon","lat")
proj4string(df) <- CRS("+proj=longlat")
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
polys <- as.SpatialPolygons.GridTopology(grd)
proj4string(polys) <- CRS("+proj=longlat")
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?