Stacking Rasters into a Multidimensional Time-Series

This R script merges multiple GeoTIFF files into a single, multi-layer raster object, assigns a time dimension to each layer, and exports the result as both a multi-layer TIFF and a NetCDF file. The workflow simplifies the handling and analysis of time-series geospatial data, making it easier to monitor changes over time. 

# Install and load required packages --------------------------------------

# Uncomment the next two lines if you need to install these packages

# install.packages("terra")

# install.packages("ncdf4")


# Load necessary libraries

library(terra)

library(ncdf4)


# Check for TIFF files in directory ---------------------------------------

# List all TIFF files from the specified directory

raster_files <- list.files(

  path = "C:/Users/", # Replace with actual file path

  pattern = "\\.tif$"# Filter for .tif files only

  full.names = TRUE

)


# Check the output

print(raster_files)


# Create multi-layer raster -----------------------------------------------

# Create a multi-layer raster from the list of TIFF files

multi_layer_raster <- rast(raster_files)


# Assign meaningful layer names -------------------------------------------

# Set custom names for each raster layer based on corresponding years

years <- 1986:2023 # set year range of data

names(multi_layer_raster) <- as.character(years)


# Add time dimension to raster --------------------------------------------

# Assign the years as a time dimension to the raster layers

time(multi_layer_raster, tstep = "years") <- years


# Verify the time dimension has been set

print(time(multi_layer_raster))


# Save raster outputs -----------------------------------------------------

# Save the combined multi-layer raster as a TIFF file

writeRaster(multi_layer_raster, "new multilayer file name.tif", overwrite = TRUE) # set file name


# Export the multidimensional raster as a NetCDF file

writeCDF(multi_layer_raster, "RAP_multidimensional_WhiteSands.nc", overwrite = TRUE) # set file name