这是一种选择:
library(raster)
# Vector of dates
dates <- format(seq(as.Date('1999/1/11'), as.Date('2006/1/10'), by='month'), '%Y%m')
# RasterStack with random data
s <- setNames(stack(replicate(length(dates), raster(matrix(runif(100), 10)))),
paste0('rain', dates))
# Create a SpatialPointsDataFrame with some random dates and coords
d <- data.frame(x=runif(10), y=runif(10), date=sample(dates, 10))
coordinates(d) <- ~x+y
# Split the spdf by date
d_by_date <- split(d, d$date)
# Extract values
rain_sum <- unsplit(lapply(d_by_date, function(x) {
# current year
y <- as.numeric(substr(x$date, 1, 4))
# current month
m <- as.numeric(substr(x$date, 5, 6))
# if month is after Oct, start from that year's Oct
# if month is before Oct, start from previous year's Oct
if(m < 11) y <- y-1
start_date <- as.Date(sprintf('%s/10/01', y))
# if start_date is earlier than first time slice, reset to first time slice
start_date <- max(min(as.Date(sub('rain', '01', names(s)), '%d%Y%m')), start_date)
end_date <- as.Date(paste0(x$date, '01'), '%Y%m%d')
# Sequence of dates to sum over
i <- format(seq(start_date, end_date, by='month'), 'rain%Y%m')
# Extract values and sum
sum(extract(s[[i]], x))
}), d$date)