---
title: "Accessing 'Rangeland Analysis Platform' (RAP) Products with R"
knit: litedown:::knit
vignette: >
  %\VignetteIndexEntry{Accessing 'Rangeland Analysis Platform' (RAP) Products with R}
  %\VignetteEngine{litedown::vignette}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
EVAL <- as.logical(Sys.getenv("R_RAPR_EXTENDED_EXAMPLES", unset=FALSE))
litedown::reactor(
  eval = EVAL,
  collapse = TRUE,
  fig.width = 6,
  fig.align = 'center'
)
```

```{r setup}
library(rapr)    # access RAP products
library(terra)   # spatial data handling
```

First, we buffer 1000 meters around a longitude/latitude coordinate (WGS84 decimal
degrees) using the {terra} package.

Change the buffering distance to include different extents around a point.

```{r} 
p <- buffer(terra::vect(
  data.frame(x = -105.97133, y = 32.73437),
  geom = c("x", "y"),
  crs = "OGC:CRS84"
), width = 1000)
```

You can change the coordinates your favorite range spot!

We can interactively inspect the area of interest, for example using
`terra::plet()` {leaflet} map:

```{r, eval=(EVAL && requireNamespace("leaflet", quietly=FALSE)), fig.width = 7}
terra::plet(p, tiles = c("Esri.WorldImagery", "OpenTopoMap"))
```

Then we use {rapr} to download the 'Rangeland Analysis Platform'
"vegetation-biomass" product for 1986 to 2024 using the polygon `p` to
define the area of interest.

```{r}
rap <- get_rap(
  p,
  product = "vegetation-biomass",
  years = 1986:2024,
  verbose = FALSE
)
```

Once that's done, let's look at the first layer:

```{r}
plot(rap[[1]], main = names(rap)[1])
```

## Animated Plots

Now we will select just the `"annual forb and grass biomass"` layers, iterate
over them, and plot. We are symbolizing with a common range of `[0,500]` pounds
per acre so the color scheme is consistent from year to year.
We write this iteration into a function called `makeplot()` and use {gifski} to
render an animated GIF file from the R plot graphics output in each year for a
total of `r length(grep("annual_forb_and_grass", names(rap)))` layers.

```{r}
makeplot <- function() {
  lapply(grep("annual_forb_and_grass", names(rap)), function(i) {
    terra::plot(
      rap[[i]],
      main = names(rap)[i],
      type = "continuous",
      range = c(0, 500),
      cex.main = TRUE
    )
    terra::plot(
      terra::as.lines(p),
      col = "white",
      add = TRUE
    )
  })
}
```

Using the {gifski} package `save_gif()` function we can easily create an animated graphic of the RAP predictions:

```{r, eval=(EVAL && requireNamespace("gifski", quietly=FALSE))}
try({
  
library(gifski) 
gifski::save_gif(makeplot(), 
                 gif_file = "annual_forb_and_grass_biomass.gif", 
                 delay = 0.5)

})
```

```{r, echo=FALSE, results='asis'}
if (file.exists("annual_forb_and_grass_biomass.gif")) {
  cat("![](annual_forb_and_grass_biomass.gif)")
}
```

## Tabular data

Finally, we will use {rapr} to download mean fractional vegetation cover values 
(% cover) from 1995 to 2025, again using the polygon `p` to define the area of interest.

```{r}
rap_tab <- get_rap_table(
  p,
  product = "cover",
  years = 1995:2025
)
```

Once the vegetation cover data has finished downloading, let's look at the table:

```{r}
print(rap_tab)
```

and plot mean `"PFG"` (Perennial Forb and Grass cover) over those 20 years:

```{r}
plot(rap_tab$year, 
     rap_tab$PFG, 
     xlab="Year", 
     ylab="Perennial Forb and Grass cover (%)", 
     type="l")
```