I am trying to import a netCDF
file into a RasterBrick
in R
. The netCDF
file has 3 dimensions.
library(ncdf)
nc <- open.ncdf("fm100_2003.nc");
print(nc)
[1] "file fm100_2003.nc has 3 dimensions:"
[1] "lon Size: 1386"
[1] "lat Size: 585"
[1] "day Size: 365"
[1] "------------------------"
[1] "file fm100_2003.nc has 1 variables:"
[1] "short dead_fuel_moisture_100hr[day,lon,lat] Longname:dead_fuel_moisture_100hr Missval:-9999"
The size of the day dimension correspond to daily fuel moisture for one year (365 days). I'd like to import these into a RasterBrick
for additional analysis which is pretty straightforward with,
r <- "fm100_2003.nc"
b <- brick(r,varname="dead_fuel_moisture_100hr")
However, the issue is that the ncol
and nlayers
in the RasterBrick
are switched, which results in an incorrect rasterLayer
for each layer in the brick. The dimensions of the RasterBrick
should read 1386, 585, 505890, 365 instead of the dimensions below:
class : RasterBrick
dimensions : 1386, 365, 505890, 585 (nrow, ncol, ncell, nlayers)
resolution : 1, 0.04166667 (x, y)
extent : 37619.5, 37984.5, -124.793, -67.043 (xmin, xmax, ymin, ymax)
coord. ref. : NA
data source : fm100_2003.nc
names : X49.3960227966309, X49.3543561299642, X49.3126894632975, X49.2710227966309, X49.2293561299642, X49.1876894632975, X49.1460227966309, X49.1043561299642, X49.0626894632975, X49.0210227966309, X48.9793561299642, X48.9376894632975, X48.8960227966309, X48.8543561299642, X48.8126894632975, ...
degrees_north: 25.0626894632975, 49.3960227966309 (min, max)
varname : dead_fuel_moisture_100hr
I am wondering if there is any way to specify the dimensions when creating the RasterBrick
to avoid this problem?
I was able to figure out a solution (or perhaps work around) to the above problem.
I first import the netCDF
file into an array in R
.
dname <- "dead_fuel_moisture_100hr"
array1 <- get.var.ncdf(nc, dname)
dim(array1)
[1] 365 1386 585
The dimensions of array1 are: days, columns, rows. However, I can change the dimensions of the array:
array2<-aperm(array1, c(3, 2, 1))
dim(array2)
[1] 585 1386 365
Now the array is organized properly: rows, columns, days. At this point I can access the depth range I need (days 1 through 365) as a matrix:
fm.day.001<-array2[,,1]
...
fm.day.365<-array2[,,365]
The matrix can be converted to a raster too:
r2<-raster(nrow=585,ncol=1386,vals=fm.day.001, xmn=-124.7722, xmx=-67.06383, ymn=25.06269, ymx=49.39602)