Check out my main page
Below is code to automate the extraction of a time series from the NOAA OISST v2 dataset. This is the 1x1 grided version, not the high resolution (0.25x0.25) gridded version. You need to download the NOAA OISST data from Jan 1982 to Dec 2022, THIS WILL NOT WORK IF THOSE SPECIFIC DATES ARE NOT USED. After you have the data, all you have to do is input the Latitude and Longitude for the area you would like to extract the time series from.
library(ncdf4) # package for netcdf manipulation
library(raster) # package for raster manipulation
library(rgdal) # package for geospatial analysis
library(dbplyr)
library(tidyverse)
#Some of these packages may give you a hard time with warning messages, luckily, as long as they download they should work perfectly
site_lon <- 17.2671 #INPUT LONGITUDE
site_lat < 168.4636 #INPUT LATITUDE
nc_data <- nc_open('/Users/IP/Downloads/OISST_LR') #change this line to the pathname of your OISST data
# Open the nc and save to a text file
{
sink('gimms3g_ndvi_1982-2012_metadata.txt')
print(nc_data)
sink()
}
lon <- ncvar_get(nc_data, "lon")
lat <- ncvar_get(nc_data, "lat", verbose = F)
t <- ncvar_get(nc_data, "time")
#Tell R where to find the data for the lat, lon, and time steps
ndvi.array <- ncvar_get(nc_data, "sst") # store the data in a 3-dimensional array
fillvalue <- ncatt_get(nc_data, "sst", "_FillValue")
fillvalue
## $hasatt
## [1] TRUE
##
## $value
## [1] 32767
nc_close(nc_data)
ndvi.array[ndvi.array == fillvalue$value] <- NA
ndvi.slice <- ndvi.array[, , 1]
r <- raster(t(ndvi.slice), xmn=min(lon), xmx=max(lon), ymn=min(lat), ymx=max(lat), crs=CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs+ towgs84=0,0,0"))
r_brick <- brick(ndvi.array, xmn=min(lat), xmx=max(lat), ymn=min(lon), ymx=max(lon), crs=CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs+ towgs84=0,0,0"))
# note that you may have to play around with the transpose (the t() function) and flip() before the data are oriented correctly. In this example, the netcdf file recorded latitude on the X and longitude on the Y, so both a transpose and a flip in the y direction were required.
r_brick<- flip(r_brick, direction = 'x')
r_brick<- flip(t(r_brick), direction = 'y')
site_series <- raster::extract(r_brick, SpatialPoints(cbind(site_lon,site_lat)))
site_series<- t(site_series)
site_series<- as.data.frame(site_series)
month<- rep(c(1,2,3,4,5,6,7,8,9,10,11,12), times = 41)
Month<- data.frame(month)
year<- rep(c(1982:2022), each = 12)
Year<- data.frame(year)
site_series$Year<- year
site_series$Month<- month
site_series<- site_series %>% rename(SST = V1)
Save the time series to a nice and friendly CSV file. :)
write.csv(site_series, "sitesst.csv")