I want to grid a data frame averaging all the points in a grid box only if the number of points are more than 10. I can do the average and count the points separately with
pts <- tmp[,c("lon","lat","z")]
coordinates(pts) <- ~ lon+lat
r <- raster(ncol = 8, nrow = 3)
extent(r) <- extent(pts)
tmp_mean <- as.matrix(rasterize(pts, r, pts$sst, fun = mean))
tmp_count <- as.matrix(rasterize(pts, r, pts$sst, fun = 'count'))
but the only way I found to constrain the mean on the number of observation in each grid cell is using a for loop
for(k in 1:3){
for(l in 1:8) tmp_mean[k,l] <- ifelse(tmp_count[k,l] < 10, NA,tmp_mean[k,l])
}
Thanks