Skip to content
Prev 374677 / 398513 Next

How to average values from grid cells with coordinates

Hi lily,
It's not too hard to do it using dataframes. Getting the indexing
right is usually that hardest part:

# these values are the centers of the black cells
lat<-rep(28:38,11)
lon<-rep(98:108,each=11)
pop<-sample(80:200,121)
# just use the data.frame function
blackcells<-data.frame(lat=lat,lon=lon,pop=pop)
plot(0,type="n",xlim=c(97.5,108.5),ylim=c(27.5,38.5),
 xlab="Longitude",ylab="Latitude")
abline(h=27.5)
abline(h=lat+0.5)
abline(v=97.5)
abline(v=lon+0.5)
text(blackcells$lon,blackcells$lat,pop)
# the red cells will be centered on the corners of 4 black cells
lat2<-rep(seq(28.5,34.5,by=2),4)
lon2<-rep(seq(99.5,105.5,by=2),each=4)
redcells<-data.frame(lat=lat2,lon=lon2,value=NA)
display the red cells
rect(lon2-1,lat2-1,lon2+1,lat2+1,border="red",lwd=2)
nblackcells<-dim(blackcells)[1]
nredcells<-dim(redcells)[1]
for(redcell in 1:nredcells) {
 close4<-rep(NA,4)
 closen<-1
 for(blackcell in 1:nblackcells) {
  if(abs(blackcells[blackcell,"lat"]-redcells[redcell,"lat"]) < 1 &&
   abs(blackcells[blackcell,"lon"]-redcells[redcell,"lon"]) < 1) {
   close4[closen]<-blackcells[blackcell,"pop"]
   closen<-closen + 1
  }
 }
 cat(close4,"\n")
 redcells[redcell,"value"]<-sum(close4)/4
}
library(plotrix)
boxed.labels(redcells$lon,redcells$lat,redcells$value,col="red")

Jim