Splash1199
Splash1199

Reputation: 379

How to batch import netCDF files into R and create a RasterStack

I have >1000 netCDF files in the "data" folder of my working directory. These are rasters showing daily snow cover extent, with the date (yyyymmdd) captured in the file name.

nhtsd25e2_20120501_v01r01.nc
nhtsd25e2_20120502_v01r01.nc
nhtsd25e2_20120503_v01r01.nc
nhtsd25e2_20120504_v01r01.nc
nhtsd25e2_20120506_v01r01.nc
nhtsd25e2_20120507_v01r01.nc
nhtsd25e2_20120518_v01r01.nc
nhtsd25e2_20120520_v01r01.nc
nhtsd25e2_20120521_v01r01.nc
nhtsd25e2_20120522_v01r01.nc

When I open a singe file, I find that the name of the data field is 'Merged.Snow.Cover.Extent'

library(raster)
snow <- raster("./data/nhtsd25e2_20120522_v01r01.nc")
view(snow)

What I would like to do (and don't have the faintest idea of where to start) is to batch import the netCDF files from my "data" folder and create a RasterStack.

The caveat is that I only want to import netCDF files for snow cover between Feb 1 and July 1 of each year (so where month-day >= "0201" but <= "0701", and where year doesn't matter.

Any help is much appreciated.

Upvotes: 1

Views: 631

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47146

Get a the filenames with list.files

ff <- list.files(pattern="\\.nc$")

Here your example files

ff <- c("nhtsd25e2_20120501_v01r01.nc", "nhtsd25e2_20120502_v01r01.nc", "nhtsd25e2_20120503_v01r01.nc", "nhtsd25e2_20120504_v01r01.nc", "nhtsd25e2_20120506_v01r01.nc", "nhtsd25e2_20120507_v01r01.nc", "nhtsd25e2_20120518_v01r01.nc", "nhtsd25e2_20120520_v01r01.nc", "nhtsd25e2_20120521_v01r01.nc", "nhtsd25e2_20120522_v01r01.nc")

Extract dates/months

dates <- substr(ff, 11, 18)
months <- as.integer(substr(dates, 5, 6))

Subset to Feb to June (you can add July 1 back in if you want it)

 f <- ff[months > 1 & months < 7]

Create a RasterStack

 x <- stack(f)

Or

 x <- lapply(f, raster)
 x <- stack(f)

Upvotes: 1

Related Questions