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:


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,]   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?

  • Looks like you may be using UTM coords. Try projection(test) <- "+proj=utm +zone=17" (Note change UTM zone 17 to your zone). inside-r.org/packages/cran/raster/docs/extract
    – Aaron
    Apr 30 '15 at 11:51
  • No, that won't affect the results at all in this case, since the y query has no metadata about the projection.
    – mdsumner
    Apr 30 '15 at 12:43

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 . . .

  • 1
    The problem is in using "c" rather than "cbind". You can use cbind(3634415,5603501) and avoid coercing to a matrix. Apr 30 '15 at 14:58
  • That is kind of irrelevant, the effect is the same. cbind gives a matrix
    – mdsumner
    Apr 30 '15 at 20:37
  • 1
    Not irrelevant, efficient. cbind(x,y) rather than matrix(c(x,y), ncol = 2) Apr 30 '15 at 21:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.