[R] How to average values from grid cells with coordinates

Jim Lemon drj|m|emon @end|ng |rom gm@||@com
Wed May 16 10:45:15 CEST 2018

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:

for(i in 1:121) blackcells[[i]]<-list(lat=lat[i],lon=lon[i],pop=pop[i])
for(i in 1:121) {
 if(abs(blackcells[[i]]$lat-redcell$lat) < 1 &&
  abs(blackcells[[i]]$lon-redcell$lon) < 1) {
redcell$pop<-(blackcells[[close4[1]]]$pop +
 blackcells[[close4[2]]]$pop + blackcells[[close4[3]]]$pop +

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


On Wed, May 16, 2018 at 2:23 PM, lily li <chocold12 using gmail.com> wrote:
> Hi R users,
> I have a question about data processing. I have such a dataset, while each
> black grid cell has a few attributes and the corresponding attribute
> values. The latitude and longitude of the center of each grid cell are
> given also.
> Then I want to average the attribute values from four adjacent grid cells
> to get the average value for the center of each red grid cell. Thus, there
> are the same number of attributes, but different values. The red grid cells
> do not overlap. I was thinking to write such a script that can ID each
> black grid cell, for example, 1, 2, 3, 4, ..., then the corresponding four
> grid cells will be used to average for the red grid cell. But I just have
> the latitude and longitude, attribute values for the black cells, and also
> latitude and longitude for the red cells, how to write such a script in R.
> Could anyone give me suggestion about the work flow? Thanks very much.
> I attached the picture of the grid cells here.
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list