r-spatialecology / landscapemetrics

Landscape Metrics for Categorical Map Patterns 🗺️ in R
https://r-spatialecology.github.io/landscapemetrics
GNU General Public License v3.0
227 stars 43 forks source link

Setting focal class i #298

Closed CRyan21 closed 9 months ago

CRyan21 commented 11 months ago

I can't find how to set the focal class 'i' for various metrics (eg the cohesion metric). I especially need to know how to distinguish between the matrix an my classes of interest. Is there an argument for this? Thanks

mhesselbarth commented 9 months ago

There is no internal argument to set a focal class i. However, this is straightforward using the terra package. In the attached code I create a raster with only one focal class i=1 by setting all other cells to NA. However, please be aware that for some metrics this might change to metric value. For example, the cohesion changes because the number of total cells changes by setting the matrix NA.

library(landscapemetrics)
library(terra)
library(dplyr)

# use internal data
landscape <- terra::rast(landscapemetrics::landscape)

# calculate cohesion for all classes but pull result for class i=1 only
lsm_c_cohesion(landscape) |> 
    dplyr::filter(class == 1)
#> # A tibble: 1 × 6
#>   layer level class    id metric   value
#>   <int> <chr> <int> <int> <chr>    <dbl>
#> 1     1 class     1    NA cohesion  87.8

# create landscape with only one class of interest
landscape_na <- landscape
landscape_na[landscape_na != 1] <- NA

# metric on class and landscape level should be identical
lsm_c_cohesion(landscape_na)
#> # A tibble: 1 × 6
#>   layer level class    id metric   value
#>   <int> <chr> <int> <int> <chr>    <dbl>
#> 1     1 class     1    NA cohesion  91.6
lsm_l_cohesion(landscape_na)
#> # A tibble: 1 × 6
#>   layer level     class    id metric   value
#>   <int> <chr>     <int> <int> <chr>    <dbl>
#> 1     1 landscape    NA    NA cohesion  91.6

# BUT: Difference to metric with all classes due to different number of total cells

Created on 2023-09-29 with reprex v2.0.2