0
votes

I have around 300 rasters of climate data (annual average precipitation and temperature). Each raster represents the global average for that year. Each raster is named by respective year e.g. 1900 etc. I then have a shapefile with museum specimen information. This includes the coordinates where they were collected and the year of collection. I want to extract the climate variables for each coordinate but only when the collection year is the same as the name of the raster file. Then I need to loop this for all my rasters. So far I can extract the climate data for all coordinates using extract(1900, coordinates). Where 1900 is the name of raster and coordinates is name of shapefile.

I tried using the if command on just one raster if(coordinates$CollYear==1900, { extract(1900, coordinates) }

But this doesn’t work.

As to how I select based on the raster file name, I have no idea.

Any tips would be greatly appreciated.

1

1 Answers

1
votes

Please always provide some example data:

library(raster)
f <- system.file("external/rlogo.grd", package="raster") 
s <- stack(f, f)
names(s) <- 1900:1905
p <- matrix(c(48, 48, 48, 53, 50, 46, 54, 70, 84, 
               7, 14, 26, 29, 39, 45, 51, 56, 46), ncol=2)
p <- data.frame(p, c(1900:1905, 1904:1902))
colnames(p) <- c("lon", "lat", "year")
p

# lon lat year
#1  48   7 1900
#2  48  14 1901
#3  48  26 1902
#4  53  29 1903
#5  50  39 1904
#6  46  45 1905
#7  54  51 1904
#8  70  56 1903
#9  84  46 1902

Approach 1. Extract all values and subset later:

e <- extract(s, p[,c("lon", "lat")])

cnms <- as.numeric(gsub("X", "", colnames(e)))
j <- match(p$year, cnms)
pairs <- cbind(1:nrow(e), j)

v <- e[ pairs ] 
v
#[1] 194 161 203 221 173 174 202 179 152

Approach 2. Loop over years

vv <- rep(NA, nrow(p))
snms <- as.numeric(gsub("X", "", names(s)))
for (y in unique(p$year)) {
    i <- p$year == y
    py <- p[i, ]
    j <- which(snms == y )
    vv[i] <- extract(s[[j]], py[,c("lon", "lat")])
}
vv
#[1] 194 161 203 221 173 174 202 179 152