[GIS] Extracting point information from raster in R

rraster

I'd like to work with climate data available from here and extract values of certain locations (for which I have lat and lon).

This is what I've done so far:

library(SDMTools)
library(raster)

test <- raster(read.asc.gz("C:/.../grids_germany_annual_frost_days_1951_17.asc.gz"))

> test
class       : RasterLayer 
dimensions  : 866, 654, 566364  (nrow, ncol, ncell)
resolution  : 1000, 1000  (x, y)
extent      : 3280415, 3934415, 5237501, 6103501  (xmin, xmax, ymin, ymax)
coord. ref. : NA 
data source : in memory
names       : layer 
values      : 13, 288  (min, max)

enter image description here

Now I figured I might be looking for the extract function but:

> extract(test, c(3634415,5603501))
     [,1]
[1,]   NA
[2,]   NA

Adding the buffer argument results in:

extract(test, c(3634415,5603501), buffer=1000)
Error in .cellValues(x, y, ...) : unused argument (buffer = 1000)

Could you explain to me what I am doing wrong and how I can extract values from the raster?

Best Answer

The y argument to extract must be 2D, i.e. a matrix or a Spatial* object (or whatever).

Your y query is just an atomic numeric vector, and so is intepreted as two cell numbers (i.e. indexes), which is why you get two missing values since they are way out of bounds (cue debate about whether that kind of out of bounds should trigger a different kind of "missing").

Do this:

extract(test, matrix(c(3634415,5603501), ncol = 2))

This might seem like an obscure behaviour localized to raster, but it's the same with other standard R functions like plot. Essentially your dimensionless vector is treated in a "vectorized" way. If you give plot a non-dimensional vector (it's really not 1-D in the sense of an array, this is a bugbear in R and other languages) it actually adds its own index for the X-axis.

I wonder what extract and plot do with actual 1-D arrays with degenerate dimensions . . .

Related Question