1

I am trying to subset 8 netcdf files (one of them is here) in a foor loop according to a shorter period of time and then to save them as a new netcdf file.

I saw that other people already asked on how to subset netcdf files according to different time period (here or here) but once I do it on my netcdf files the "for loop" keeps on running without finishing (not even the first netcdf file) and I can't figure out why.

Here the code I use:

library(raster)
library(netcdf4)
library(lubridate)

#setting wd=indir containing netcdf files

setwd(indir)

files=list.files(pattern="nc")

for (j in seq_along(files)){

#setting wd containing netcdf files in the loop
setwd(indir)

b<-brick(files[j])

nc<-nc_open(files[j])

#variable
varname<-names(nc[['var']][3])
varunits <- ncatt_get(nc,varname,"units")[[2]]

lon<-ncvar_get(nc,"lon")

lat<-ncvar_get(nc,"lat", verbose = F)

time<-ncvar_get(nc, "time")

tunits <- ncatt_get(nc, "time", "units")[[2]]

dlname <- ncatt_get(nc, varname,"long_name")[[2]]

nc_close(nc)

#assigning a crs
proj4string(b)<-"+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"

#setting time as.Date 
tm<-ymd(getZ(b))

#setting time to rasterBrick
b<-setZ(b, tm)

# subsetting
b2<-subset(b, which(tm < as.Date('2006-01-01')))      

#setting wd where I want to save the "new" netcdf files
setwd(outdir)

writeRaster(b2, filename = paste0(varname, "_1971_2006_Noce.nc"),
format="CDF", varname=varname, varunit=varunits, longname=dlname,
xname="lon", yname="lat", zname="time", zunit=tunits, overwrite=TRUE)
}

Any help on how to get the loop working would be very much appreciated!

Bart
  • 9,825
  • 5
  • 47
  • 73
Cicciput
  • 11
  • 3
  • 1
    If your code is indeed `files=list.files(pattern="nc)` then you've missed a `"` to close out that string. – shians Nov 21 '18 at 23:32
  • Try adding a printed out counter at various points in your code (ie `print(j)` or `print(varname)`) throughout your loop that might tell you where it is going wrong – morgan121 Nov 22 '18 at 07:57
  • Thank you shians, but unfortunately this was just a transcription error when I copy pasted the code here. In the code itself I close out that string. – Cicciput Nov 22 '18 at 08:08
  • thanks, I have added some print(j) and now I get this error: Error in R_nc4_create: Invalid argument (creation mode was 0) Error in ncdf4::nc_create(filename, vardef, force_v4 = force_v4) : Error in nc_create! could you help me understanding why it refers to "nc_create" in writeRaster? – Cicciput Nov 22 '18 at 09:07
  • hi, your code works well for me. The only thing that I notice is that when you open the subsetted nc file the dates are not well represented. Try to UPDATE your R version and related packages as a start. – aaaaa Nov 23 '18 at 18:32

0 Answers0