Reputation: 1234
I have a raster stack/brick with 84 layers, each layer corresponding to a month of rainfall data from November 1999 to October 2006. I also have a data frame where each row contains (amongst other things) spatial coordinates and values for year and month.
I want to extract a rainfall value for each row in my data frame. To do this I need to use the year and month values to select the corresponding layer in the raster stack and then the spatial coordinates to select the appropriate value from that layer. My question comes in two parts:
1) In my data frame I have joined the year and month columns together like so:
data$date <- paste0(data$year, data$month)
I now have a single column of values which tell me the timing of that data point e.g. July 2001 would be "20017". I want to name the layers in my raster stack in the same way i.e. "199911" through "200610". I could type all 84 of these these out and then use something like:
names(rainfall) <- c("199911" ... "200610")
But there must be a more efficient way to do it?
2) Having done this how would I use the date column in my data frame to select the corresponding layer from my raster stack and then the spatial coordinates to select the location? If it was a single layer I could use:
data.sp <- data
coordinates(data.sp) <- ~ x + y
rain.points <- over(data.sp, rainfall)
data$rain <- (rain.points)
Any help would be greatly appreciated!
Upvotes: 0
Views: 5299
Reputation: 47036
Question 1: do something like this
names(rainfall) <- paste0(rep(1999:2006, each=12), 1:12)[11:94]
Question 2:
You can do
pnt <- cbind(0,0)
s <- rainfall[["200111"]]
extract(s, pnt)
but you might want to do something like what is discussed here )
Upvotes: 4