0

I wrote a function to extract values from ncdf files, as shown below:

precresults <- function(x){
    library(magrittr)
    library(ncdf4)
    library(raster)
    library(ncdf.tools)
    ##library(ncf)
    re1 <- brick(nl1a[x])
    re <- extract(re1,zuobiao)
        ####zuobiao stands for the coordinate of the targeted sites
    ###extract(zuobiao)
    return(re)
}

###precresults(20)
precresults11 <- lapply(1:420, precresults)

"lapply" function is used to extract values for multiple site.

However, an error occurs:

Error in UseMethod("extract_") : no applicable method for 'extract_' applied to an object of class "c('RasterBrick', 'Raster', 'RasterStackBrick', 'BasicRaster')"

How can we solve such error?

dww
  • 30,425
  • 5
  • 68
  • 111
  • 2
    Just a shot in the dark - is there any masking going on? Perhaps you could try using `raster::extract`. My guess is that right now, `magrittr::extract` is being used. – Roman Luštrik Aug 25 '18 at 08:15
  • Thanks a lot for your comments. I finally solve my problem based on your comments. – user8432012 Aug 26 '18 at 09:27

1 Answers1

1

I think Roman is correct, magrittr::extract is masking raster::extract. In the example provided you do not use magrittr, but you may use it elsewhere, so use raster::extract rather then extract. Your function could be rewritten as:

library(raster)
precresults <- function(x){
    re1 <- brick(nl1a[x])
    raster::extract(re1, zuobiao)
}
precresults11 <- lapply(1:420, precresults)

Or like this:

library(raster)
x <- matrix(nrow=length(zuobiao), ncol=420)
for (i in 1:420) {
    re1 <- brick(nl1a[i])
    x[,i] <- raster::extract(re1, zuobiao)
}
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63