treeandcoffee
treeandcoffee

Reputation: 1

Extract SST values from netCDF to location by date

I am totally new to R and trying to build a species distribution model.

I have a directory with files in .nc (netCDF) format that contain monthly sea surface temperature from jul 2002 to jul 2022. The folder and file name shown in the image below. enter image description here

library(ncdf4)
library(terra)
library('RNetCDF')
library(raster)
library(sp)

filenames = list.files('SST/Ocean_ColorSST_2002_2022',pattern='*.nc',full.names=TRUE)
filenames

ncfile <- nc_open(filenames[1:])

lon <- ncvar_get(nc, 'lon')
lat <- ncvar_get(nc, 'lat', verbose = F)
SST <- ncvar_get(nc, 'sst')

I have an occurrence record(34590 rows) of whale from 1970 to 2023 with column of year, month, day, latitude and longitude. enter image description here

I need to extract the sea surface temperature value to column 'SST' for each location depending on the year and month for which the location was obtained.

This is very important to the project. Please help.

Upvotes: 0

Views: 124

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47491

You do not provide sufficient information to answer your question, but the general approach, for a single file.

library(terra)

filenames = list.files('SST/Ocean_ColorSST_2002_2022',pattern='*.nc',full.names=TRUE)

r <- rast(filenames[1] ,"SST")
e <- extract(r, points)

Perhaps you can do

r <- rast(filenames ,"SST")
e <- extract(r, points)

points would be a SpatVector or matrix with the coordinates, in the same coordinate reference system as the raster data. See ?project

It seems like you need to study a bit first. See the terra manual and https://rspatial.org

Upvotes: 0

Related Questions