## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>",
                      fig.width = 6, fig.height = 4.5)

## ----setup, include = FALSE---------------------------------------------------
library(sptrends)
r <- terra::rast(
  sort(list.files(
    example_data("vhp_ndvi"),
    pattern = "\\.tif$",
    full.names = TRUE
  ))
)

## -----------------------------------------------------------------------------
mk <- trend_test(r, method = "MK", report = FALSE, verbose = FALSE)
cmk <- trend_test(r, method = "CMK", report = FALSE, verbose = FALSE)
mk
cmk

## ----fig.width = 10, fig.height = 4.8, fig.alt = "Global comparison of uncorrected MK and CMK trend directions in annual mean NDVI"----
direction_class <- function(result) {
  statistic <- if ("Sm" %in% names(result$stats)) {
    result$stats$Sm
  } else {
    result$stats$S
  }
  significant <- result$stats$p <= 0.05
  terra::ifel(
    significant & statistic < 0,
    -1,
    terra::ifel(significant & statistic > 0, 1, 0)
  )
}

direction <- c(direction_class(mk), direction_class(cmk))
names(direction) <- c("MK", "CMK (3 × 3)")
terra::plot(
  direction,
  type = "classes",
  breaks = c(-1.5, -0.5, 0.5, 1.5),
  col = c("#1f77b4", "#D9D9D9", "#d62728"),
  plg = list(legend = c("Decrease", "No change", "Increase")),
  reverse = TRUE,
  nc = 2
)

## ----eval = FALSE-------------------------------------------------------------
# trend_5 <- trend_test(r, window_size = 5L)

