Skip to content
Prev 374626 / 398513 Next

How to average values from grid cells with coordinates

Hi lily,
There are one or two assumptions to be made here. First is that the
latitude and longitude values of the "black" cells are equally spaced
as in your illustration. Second, that all latitude and longitude
values for the "red" cells fall at the corners of four "black" cells.

You can get the four "black" cells by finding the lat/lon values that
are closest to the "red" lat/lon values. Here's a basic example:

lat<-rep(28:38,11)
lon<-rep(98:108,each=11)
pop<-sample(80:200,121)
blackcells<-list()
for(i in 1:121) blackcells[[i]]<-list(lat=lat[i],lon=lon[i],pop=pop[i])
redcell<-list(lat=33.5,lon=100.5,pop=NA)
close4<-rep(NA,4)
closen<-1
for(i in 1:121) {
 if(abs(blackcells[[i]]$lat-redcell$lat) < 1 &&
  abs(blackcells[[i]]$lon-redcell$lon) < 1) {
  close4[closen]<-i
  closen<-closen+1
 }
}
cat(close4,"\n")
redcell$pop<-(blackcells[[close4[1]]]$pop +
 blackcells[[close4[2]]]$pop + blackcells[[close4[3]]]$pop +
 blackcells[[close4[4]]]$pop)/4
print(blackcells[[close4[1]]])
print(blackcells[[close4[2]]])
print(blackcells[[close4[3]]])
print(blackcells[[close4[4]]])
print(redcell)

As you can see, this has picked out the four "black" cells closest to
the "red" cell's coordinates and calculated the mean.

Jim
On Wed, May 16, 2018 at 2:23 PM, lily li <chocold12 at gmail.com> wrote: