Netcdf data in R

Could someone please tell me how to deal with this error?
setwd(‘C:/Users/harto/Desktop/Housna’)
library(readr)
library(dplyr)
library(tidyr)
library(ggplot2)
library(ggmap)
library(viridisLite)
library(weathermetrics)
library(ncdf4)
library(chron)
library(RColorBrewer)
library(lattice)
library(viridis)
ncin ← nc_open(“precip.nc”)
lon<- ncvar_get(ncin,“longitude”)
lat<- ncvar_get(ncin, “latitude”)
tmp.array<- ncvar_get(ncin,“tp”)
dunits ← ncatt_get(ncin,“tp”,“units”)
dunits
tmp.array<- tmp.array*1000
dim(tmp.array)
tunits ← ncatt_get(ncin, “time”,“units”)

tmp.slice ← tmp.array[,1]
nc_close(ncin)
image(lon,lat,tmp.slice)
tas ← tmp.array [, , m] #note this is the same as above
mapCDFtemp ← function(lat,lon,tas) #model and perc should be a string

tmp.slice ← tmp.array[,1]
Error in tmp.array[, , 1] : incorrect number of dimensions

I think you have an error with

tmp.slice ← tmp.array[,1]

That line occurs twice, but weirdly the second line is after a dangling (it’s incomplete) definition of a function “mapCDFtemp”. So, I’m only considering the context up to the first instance of that line. (The code above would not parse in an R interpreter (it would as a sourced script but still, doesn’t make sense as-is)).

So, the error is I think that tmp.array is 3D - have a look at dim(tmp.array), it should have 3 elements, the length of ‘lon’, the length of ‘lat’, and the number of elements in the third dimension of “tp” (which I think we can assume is non-degenerate and > 1.

Try

tmp.slice <- tmp.array[,,1]

note the third position for the index, because it’s “3D”. tmp.slice should now be “2D”, see dim(tmp.slice). The degenerate length-1 dim was dropped, by default.

All that said, I would ignore the fact that it’s netcdf entirely and use common higher level R idioms like

library(terra)
r <- rast("precip.nc", "tp")
plot(r[[1]])

but, without the file I’m guessing only at what might work. HTH

1 Like