Search code examples
rrasternetcdf

NetCDF to Raster Brick "Unable to find inherited method for function 'brick' for 'ncdf4'"


Really simple problem with the raster package, also using ncdf4 to load in an ECMWF Era-Interim Netcdf file.

Simply doing this:

a <- nc_open("SSTs.nc")
B <- brick(a, varname="sst")

Returns this:

    Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ‘brick’ for signature ‘"ncdf4"’

The file is just SST data over the whole globe, for 1 month (Jan2016). When I convert it into an array (i.e. extract dimensions/variable, and convert time to UTC, shove it into an array) I don't get the same error, but the raster package says it supports .nc files straight in (so long as they're cf-1 compatible, which Era-Interim .nc's are)

Any help much appreciated, have tried this with many Netcdf files (non-Era Interim too).


Solution

  • thank Renaud Lancelot, who give clearly source code. I have modified his code to fit with your data

     # load package
     library(sp)
     library(raster)
     library(ncdf4)
    
     # read ncdf file
     nc<-nc_open('D:/SSTs.nc')
    
     # extract variable name, size and dimension
     v <- nc$var[[1]]
     size <- v$varsize
     dims <- v$ndims
     nt <- size[dims]              # length of time dimension
     lat <- nc$dim$latitude$vals   # latitude position
     lon <- nc$dim$longitude$vals  # longitude position
    
     # read sst variable
     r<-list()
     for (i in 1:nt) {
       start <- rep(1,dims)     # begin with start=(1,1,...,1)
       start[dims] <- i             # change to start=(1,1,...,i) to read    timestep i
       count <- size                # begin with count=(nx,ny,...,nt), reads entire var
       count[dims] <- 1             # change to count=(nx,ny,...,1) to read 1 tstep
    
       dt<-ncvar_get(nc, varid = 'sst', start = start, count = count)
    
       # convert to raster
       r[i]<-raster(dt)
     }
    
     # create layer stack with time dimension
     r<-stack(r)
    
     # transpose the raster to have correct orientation
     rt<-t(r)
     extent(rt)<-extent(c(range(lon), range(lat)))
    
     # plot the result
     spplot(rt)