I am using satellite data to look at light levels in the surface ocean. (any data from here works as I'm just trying to understand how to open and work with the data)
In the code below, I saved all the .nc
files in a folder on my desktop then imported it all under files
then started a loop to open the file.
Is there a way to 1) crop the data extent(-180, -176, -40, -36)
then 2) extract the lat, Lon and par values? Im guessing that there is multiple depths available, but I dont know how to check that.
library(raster)
setwd("/Users/AquaModis_PAR")
nc.data<-list()
files<-list.files(pattern = ".nc",full.names=TRUE)
df=NULL
for(i in seq_along(files)) {
par[i] = brick(files[i], stopIfNotEqualSpaced = FALSE, varname = "par")
}
To load and crop the data do something like this:
library(raster)
files <- list.files(pattern = ".nc", full.names=TRUE)
region <- extent(-180, -176, -40, -36)
data <- lapply(files, function(path) {
# Load and crop.
d <- brick(path, stopIfNotEqualSpaced = FALSE, varname = "chlor_a") |>
crop(region)
# Get raster values.
values <- getValues(d)
# Get coordinates.
coords <- coordinates(d)
cbind(coords, values) |>
data.frame() |>
setNames(c("lon", "lat", "value")) |>
na.omit()
})
Look at the data from the first file:
> head(data[[1]])
lon lat value
28 -178.8542 -36.02084 0.06653178
29 -178.8125 -36.02084 0.06850998
30 -178.7708 -36.02084 0.07330192
31 -178.7292 -36.02084 0.07878597
34 -178.6042 -36.02084 0.07993947
35 -178.5625 -36.02084 0.08084643
There are probably more elegant ways to extract the data to a data frame, but this does the job.
The na.omit()
at the end is to drop records where the value is missing (there were quite a few in the data I looked at).
For completeness, these are the files I tested it on:
AQUA_MODIS.20030101.L3m.DAY.CHL.chlor_a.4km.nc
AQUA_MODIS.20030102.L3m.DAY.CHL.chlor_a.4km.nc
AQUA_MODIS.20030103.L3m.DAY.CHL.chlor_a.4km.nc