Skip to content

Allow users to use b3gbi functions as input #75

@wlangera

Description

@wlangera

This only works for time series indicators (_ts).
It also won't work wrapped in another function (to get function name)?

  # Load package
library(b3gbi)
#> Warning: package 'b3gbi' was built under R version 4.5.2

# Load and prepare the GBIF data cube
cube_name <- system.file("extdata", "denmark_mammals_cube_eqdgc.csv",
                         package = "b3gbi")
mammal_data <- process_cube(cube_name)

# Calculate indicator from dataframe
trans_b3gbi_function <- function(f, data) {
  # Try to read the argument as it was written in the call
  mc <- match.call()
  arg <- mc$f
  
  # Determine the class name passed by the user
  if (is.character(arg)) {
    fname <- arg
  } else if (is.name(arg)) {
    fname <- as.character(arg)
  } else {
    stop("f must be a string or an unquoted symbol.")
  }
  
  # Parse suffix (_ts or _map)
  if (grepl("_ts$", fname)) {
    suffix <- "ts"
  } else if (grepl("_map$", fname)) {
    suffix <- "map"
  } else {
    stop("Class name must end in '_ts' or '_map'")
  }
  
  # Assign class to the data
  cls_base <- sub("_(ts|map)$", "", fname)
  class(data) <- c(fname, cls_base, class(data))
  
  # Build function name: calc_<suffix>.<base>
  fun_name <- paste0("calc_", suffix, ".", cls_base)
  
  # Fetch from b3gbi namespace
  fun <- get(fun_name, envir = asNamespace("b3gbi"))
  
  # Execute dispatch function
  fun(data)
}

# 1) pass symbol (recommended)
trans_b3gbi_function(obs_richness_ts, mammal_data$data)
#> # A tibble: 126 × 2
#>     year diversity_val
#>    <dbl>         <int>
#>  1  1862             1
#>  2  1863             1
#>  3  1870             1
#>  4  1874             1
#>  5  1879             1
#>  6  1881             2
#>  7  1884             3
#>  8  1886             1
#>  9  1894             1
#> 10  1896             1
#> # ℹ 116 more rows

# 2) pass as string
trans_b3gbi_function("obs_richness_ts", mammal_data$data)
#> # A tibble: 126 × 2
#>     year diversity_val
#>    <dbl>         <int>
#>  1  1862             1
#>  2  1863             1
#>  3  1870             1
#>  4  1874             1
#>  5  1879             1
#>  6  1881             2
#>  7  1884             3
#>  8  1886             1
#>  9  1894             1
#> 10  1896             1
#> # ℹ 116 more rows

Created on 2025-12-08 with reprex v2.1.1

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions