The main thing you want to do is reshape your data so that it is in long format, and convert the dates so that you can perform arithmetic on them. This is what we do here:
library(reshape2)
df.mlt <- melt(df, id.vars=c("lat", "lon", "dt"))
df.mlt[c("dt", "variable")] <- lapply(df.mlt[c("dt", "variable")], function(x) as.Date(paste0(x, "01"), format="x%Y%m%d"))
library(data.table)
data.table(df.mlt)[(dt - variable) %between% c(0, 190), mean(value), by=list(lat, lon, dt)]
Look at df.mlt
to see what I mean by long format (basically, the columns become rows). The second command just converts the two columns dt
, and variable
(variable
holds the names of what used to be columns before the melt) into date format. Finally, I use data.table
to select the appropriate rows (date difference must be less than 190, which I take to be a proxy for six months assuming your data is monthly this should be safe) and to compute statistics on row groups (you could also use dplyr
or other "split/apply/combine" style techniques). This produces:
lat lon dt V1
1: -34.0 144.0 2001-06-01 6.016667
2: -34.5 144.5 2001-07-01 10.314286
3: -35.0 145.0 2001-08-01 16.328571
4: -35.5 145.5 2001-09-01 14.700000
5: -36.0 146.0 2001-10-01 18.214286
6: -36.5 146.5 2001-11-01 20.442857
7: -37.0 147.0 2001-12-01 20.342857
update: apparently I can't count: these are averages of six months, as per your question.