library(terra)
2 HDF4 format
2.1 NetCDF (Network Common Data Form)
Layers in the file can be listed using the nc_open()
function:
<- here::here("data", "avhrr-only-v2.20160503.nc") file
2.1.1 Open NetCDF file using rast()
The terra
package provides an alternative method to work with NetCDF files. This creates a SpatRaster
object, which is more memory-efficient for large datasets.
To see which layers are available in the file, use the describe()
function. Note the var
column in the output:
describe(file, sds = TRUE)
id | name | var | desc | nrow | ncol | nlyr |
---|---|---|---|---|---|---|
1 | NETCDF:“/media/LaCie16TB/work/projects/documentation/read_rs_product/data/avhrr-only-v2.20160503.nc”:sst | sst | [1x1x720x1440] sst (16-bit integer) | 720 | 1440 | 1 |
2 | NETCDF:“/media/LaCie16TB/work/projects/documentation/read_rs_product/data/avhrr-only-v2.20160503.nc”:anom | anom | [1x1x720x1440] anom (16-bit integer) | 720 | 1440 | 1 |
3 | NETCDF:“/media/LaCie16TB/work/projects/documentation/read_rs_product/data/avhrr-only-v2.20160503.nc”:err | err | [1x1x720x1440] err (16-bit integer) | 720 | 1440 | 1 |
4 | NETCDF:“/media/LaCie16TB/work/projects/documentation/read_rs_product/data/avhrr-only-v2.20160503.nc”:ice | ice | [1x1x720x1440] ice (16-bit integer) | 720 | 1440 | 1 |
This file contains four layers: sst
, anom
, err
, and ice
. They can be opened using the rast()
function using the lyrs
or subds
argument.
TODO: Explain the difference between lyrs
and subds
.
2.1.1.1 Open a specific layer using lyrs
# To open the sst layer
<- rast(paste0("NETCDF:", file, ":sst"))
sst_layer
# To open the anom layer
<- rast(paste0("NETCDF:", file, ":anom"))
anom_layer
# To open the err layer
<- rast(paste0("NETCDF:", file, ":err"))
err_layer
# To open the ice layer
<- rast(paste0("NETCDF:", file, ":ice")) ice_layer
2.1.1.2 Open a specific layer using subds
# To open the sst layer
<- rast(file, subds = "sst")
sst_layer
# To open the anom layer
<- rast(file, subds = "anom")
anom_layer
# To open the err layer
<- rast(file, subds = "err")
err_layer
# Open the ice layer
<- rast(file, subds = "ice") ice_layer
2.1.2 Plotting
We can visualize the layers using the plot()
function:
par(mfrow = c(2L, 2L))
plot(sst_layer, main = "SST")
plot(anom_layer, main = "Anomaly")
plot(err_layer, main = "Error")
plot(ice_layer, main = "Ice")
It looks like the raster is rotated. We can rotate it back with the rotate()
function:
<- rotate(sst_layer)
sst_layer
plot(sst_layer)
Converting to a data frame can be useful for certain types of analysis or visualization, but be cautious with large datasets as this can be memory-intensive.
<- as.data.frame(sst_layer)
df
head(df)
sst_zlev=0 |
---|
-1.7 |
-1.7 |
-1.7 |
-1.7 |
-1.7 |
-1.7 |