Error while converting netcdf data into a raster brick

227 Views Asked by At

I'm trying to visualize monthly averages of RegCM output I joined using CDO but I'm not being able to do it.

In order to do that I was trying to find a way to plot de monthly averages of my variable "pr" as you could do using GrADS.

I found that a way to do this was using the brick function and the raster library. So I was trying to use the code suggested in another question to convert my netcdf file into a raster brick: NetCDF to Raster Brick "Unable to find inherited method for function 'brick' for 'ncdf4'"

# load package
 library(sp)
 library(raster)
 library(ncdf4)

 # read ncdf file
 nc<-nc_open('dat.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$xlat$vals   # latitude position
 lon <- nc$dim$xlong$vals  # longitude position

 # read pr 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 = 'pr', 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)

But once I tried to run the for loop in the code, I get the following error:

Error in ncvar_get_inner(ncid2use, varid2use, nc$var[[li]]$missval, addOffset,  : 
  Error: variable has 3 dims, but start has 2 entries.  They must match!

The file I'm trying to visualize can be found in the following link: https://drive.google.com/file/d/13KsOpnt-Wk2v93WwGcOU6AHw8KGOFlai/view?usp=sharing

I would really appreciate any insights with this problem!

0

There are 0 best solutions below