Skip to content
Prev 27966 / 29559 Next

Request for help about running a loop and reading .NC files

Hi,

Rolf is correct that you might consider enclosing your nc_open(...) with
try(nc_open(...)), and then testing if the value returned by try() inherits
from the "try-error" class. If there is no problem opening the NCDF file,
then it will return an "ncdf4" class object.

Also, you might isolate the file extraction stuff into a function to make
your life easier. Something like this (obviously not tested)...


### START
# extract data from a NCDF file
# @param filename the path and name of the file
# @return either NULL (for an exception) or a data.frame
extract_from_nc <- function(filename){

  nc <- try(nc_open(filename))
  if (inherits(nc, "try-error")){
    # if it isn't a healthy NCDF file you will be here
    x <- NULL
  } else {
    # otherwise you will be here and you can run your extraction
    mean1 <- ...
     ...
    x <- as.data.frame(mean_chl_df)
    write.csv(x, ... other stuff here ...)
    nc_close(nc)
  }
  return(x)
}

flist <- list.files(path ="NCFiles/", pattern = "^.*\\.(nc|NC|Nc|Nc)$",
full.names = TRUE)

xx <- lapply(flist, extract_from_nc)
ix <- sapply(xx, is.null)                    # find the NULLS
xx <- xx[!ix]                                # remove them (if any)
if (length(xx) > 0) x <- do.call(rbind, xx)  # row bind what remains into
one data frame (in case that is helpful)
### END

I hope that helps.

Cheers,
Ben





On Mon, Mar 23, 2020 at 5:53 PM Bhaskar Mitra <bhaskar.kolkata at gmail.com>
wrote: