Reputation: 1441
I'm trying to extract sea surface temperature data from a series of .nc files. So I have one folder containing the 30 downloaded .nc files all written like "1981.nc", "1982.nc" and so on.
But rather than load them all in individually I want to loop over each one and calculate the mean temperature for each file so I'd have 30 values of temperature at the end.
The problem is the year in date arguments have to change for each file. I thought of including something like years<-substr(filenames, 1,4)
on the files which extracts the value of the year but it doesn't work.
I was thinking of something along the following lines:
library(ncdf4)
setwd("C:\\Users\\Desktop\\sst")
source("C:\\Users\\Desktop\\NOAA_OISST_ncdf4.R")
out.file<-""
filenames <- dir(pattern =".nc")
years<-substr(filenames, 1,4)
lst <- vector("list", length(filenames ))
for (i in 1:length(filenames)) {
ssts = extractOISSTdaily(filenames[i], "C:\\Users\\Desktop\\lsmask.oisst.v2.nc",
lonW=350,lonE=351,latS=52,latN=56,date1='years[i]-11-23', date2='years[i]-12-31')
mean(ssts)
}
The extractOISSTdaily
function to do the extracting is described here: http://lukemiller.org/index.php/2014/11/extracting-noaa-sea-surface-temperatures-with-ncdf4/
The .nc files are here: https://www.esrl.noaa.gov/psd/data/gridded/data.noaa.oisst.v2.highres.html#detail
Upvotes: 1
Views: 98
Reputation: 12074
Does this work?
# Get filenames
filenames <- dir(pattern =".nc")
# Mean SSTs
m.ssts <- NULL
# Loop through filenames
for (i in filenames) {
# Get year (assuming form of filename is, e.g., 1981.nc)
year <- sub(".nc", "", i)
# Do whatever this function does
ssts <- extractOISSTdaily(i, "C:\\Users\\Desktop\\lsmask.oisst.v2.nc",
lonW=350, lonE=351, latS=52, latN=56,
date1=paste(year, "-11-23", sep = ""),
date2=paste(year, "-12-31", sep = ""))
# Profit!
m.ssts <- c(m.ssts, mean(ssts))
}
The code works by first collecting all filenames in the current directory with the extension .nc
and creating an empty object in which to store the mean SSTs. The for loop goes through the filenames in turn stripping off the files extension to get the year (i.e., 1981.nc
becomes 1981
) by substituting an empty string in place of .nc
. Next, the netCDF data for the specified interval is placed in ssts
. The interval is created by pasting together the current year with the desired month and day. Finally, the mean is calculated and appended to the m.ssts
object. As the OP says below, this should actually read m.ssts <- c(m.ssts, mean(ssts, na.rm = TRUE))
to allow for NA
in the data.
Upvotes: 1