r-spatialecology/landscapemetrics

calculate_lsm error

Opened this issue · 4 comments

the problem occurred when there is one pixel of some class

Thank you a lot @xkucm! I was able to locate and fix the issue -- it was in lsm_p_gyrate():

library(landscapemetrics)
library(terra)
#> terra 1.7.73
landscape = as.matrix(read.table("https://github.com/r-spatialecology/landscapemetrics/files/14546014/landscape.csv"))
landscape = rast(landscape)

lsm_p_gyrate(landscape)
#> Error in names(object) <- nm: 'names' attribute [3] must be the same length as the vector [2]

@xkucm you can install my fix with remotes::install_github("r-spatialecology/landscapemetrics@fixes_lsm_p_gyrate):

library(landscapemetrics)
library(terra)
#> terra 1.7.73
landscape = as.matrix(read.table("https://github.com/r-spatialecology/landscapemetrics/files/14546014/landscape.csv"))
landscape = rast(landscape)

lsm_p_gyrate(landscape)
#> # A tibble: 404 × 6
#>    layer level class    id metric value
#>    <int> <chr> <int> <int> <chr>  <dbl>
#>  1     1 patch     0     1 gyrate 1.68 
#>  2     1 patch     0     2 gyrate 0.654
#>  3     1 patch     0     3 gyrate 3.86 
#>  4     1 patch     0     4 gyrate 0.975
#>  5     1 patch     0     5 gyrate 0    
#>  6     1 patch     0     6 gyrate 2.25 
#>  7     1 patch     0     7 gyrate 0    
#>  8     1 patch     0     8 gyrate 5.04 
#>  9     1 patch     0     9 gyrate 6.98 
#> 10     1 patch     0    10 gyrate 2.21 
#> # ℹ 394 more rows

calculate_lsm(landscape)
#> Warning: Please use 'check_landscape()' to ensure the input data is valid.
#> Warning: NAs introduced by lsm_c_nlsi.
#> Warning: Class 1: PAFRAC = NA for class with < 10 patches
#> Warning: Class 5: PAFRAC = NA for class with < 10 patches
#> Warning: No maximum number of classes provided: RPR = NA
#> # A tibble: 5,244 × 6
#>    layer level class    id metric  value
#>    <int> <chr> <int> <int> <chr>   <dbl>
#>  1     1 class     0    NA ai       75.6
#>  2     1 class     1    NA ai       78.8
#>  3     1 class     2    NA ai       60.5
#>  4     1 class     3    NA ai       63.0
#>  5     1 class     4    NA ai       72.7
#>  6     1 class     5    NA ai       NA  
#>  7     1 class     0    NA area_cv 166. 
#>  8     1 class     1    NA area_cv  NA  
#>  9     1 class     2    NA area_cv 297. 
#> 10     1 class     3    NA area_cv 169. 
#> # ℹ 5,234 more rows

Hi @mhesselbarth -- see @319. In short, R drops dimensions in mapply() when they only have one row:

# two points
points = matrix(c(1, 2, 3, 4), ncol = 2)
dim(points)
#> [1] 2 2
points <- mapply(FUN = `*`, data.frame(points), c(1, 1))
dim(points)
#> [1] 2 2

# one point
points = matrix(c(1, 2), ncol = 2)
dim(points)
#> [1] 1 2
points <- mapply(FUN = `*`, data.frame(points), c(1, 1))
dim(points)
#> NULL

I added a quick fix -- but maybe you can think of something better there?