0

I am trying to get some elevations for bird locations I have in NZ. I thought I might use the code provided as an answer to a similar question (Extracting elevation from website for lat/lon points in Australia, using R), unfortunately I get errors when using the extract function in the raster package, even though the code is almost identical.

library(raster)
m <- data.frame(lon = c(172.639847, 173.283966), lat = c(-43.525650, -41.270634))
x <- getData('alt', country = "NZL")
cbind(m, alt = extract(x, m))
plot(x)
points(m)

ERROR:

cbind(m, alt = extract(x, m))
Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ‘extract’ for signature ‘"list", "data.frame"’

Can anyone tell me what is going wrong? I have been searching for hours but cannot find a solution.

Thanks, Sam

SKrouse
  • 3
  • 1
  • 2

1 Answers1

2

I don't know exactly why, but the subtle reason is that, compared to Australia, getData returns a different data structure for New Zealand. It returns a list, where the RasterLayers are in the first (and second) list element:

library(raster)

## Australia ==============
m <- data.frame(lon = c(146.9442, 146.4622), lat = c(-36.0736, -36.0491))
aus <- getData('alt', country = "AUS")
class(aus)
# [1] "RasterLayer"
# attr(,"package")
# [1] "raster"
cbind(m, alt = extract(aus, m))


## New Zealand ============
m <- data.frame(lon = c(172.639847, 173.283966), lat = c(-43.525650, -41.270634))
nzl <- getData("alt", country = "NZL")
> class(nzl) # is a list!
# [1] "list"
> class(nzl[[1]])
# [1] "RasterLayer"
# attr(,"package")
# [1] "raster"
cbind(m, alt = extract(nzl[[1]], m))
cbind(m, alt = extract(nzl[[2]], m))

tpetzoldt
  • 5,338
  • 2
  • 12
  • 29