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

浪尽此生 提交于 2019-12-06 11:29:44

问题


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


回答1:


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)


来源:https://stackoverflow.com/questions/42982599/netcdf-to-raster-brick-unable-to-find-inherited-method-for-function-brick-for

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!