How to average values from grid cells with coordinates
Hi lili,
You can extend it like this. I checked this with two values each for
pop and mood, and it looked okay. Obviously I didn't check the result
with 365 values for each, but it ran okay.
# these values are the centers of the black cells
lat<-rep(28:38,11)
lon<-rep(98:108,each=11)
pop<-matrix(sample(80:200,44165,replace=TRUE),ncol=365)
colnames(pop)<-paste0("pop",1:365)
mood<-matrix(sample(1:10,44165,replace=TRUE),ncol=365)
colnames(mood)<-c("mood",1:365)
# create the data frame for the black cells
blackcells<-cbind(data.frame(lat=lat,lon=lon),pop,mood)
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)
# 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)
popmat<-matrix(NA,nrow=16,ncol=365)
colnames(popmat)<-paste0("pop",1:365)
moodmat<-matrix(NA,nrow=16,ncol=365)
colnames(moodmat)<-paste0("mood",1:365)
redcells<-cbind(data.frame(lat=lat2,lon=lon2),popmat,moodmat)
#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]<-blackcell
closen<-closen + 1
}
}
redcells[redcell,3:730]<-colMeans(blackcells[close4,3:730])
}
Jim
On Tue, May 22, 2018 at 1:37 PM, lily li <chocold12 at gmail.com> wrote:
Hi Jim, Thanks. It works. I now have more complex problems. If at each blackcell, there are two variables such as pop and mood. For each variable, there are daily records in one year, so 365 records for pop and 365 records for mood. The averaged values for the redcells should be daily records too. What kind of format do you recommend for this problem? Right now, I just get the latitudes and longitudes into a dataframe. Thanks.