library(funrar)
library(biodivTS)

Calculate functional distinctiveness for each species based on the species pool (defined by all species observed over the course of the timeseries)

Get data

pins::board_register_github(name = "github", repo = "karinorman/biodivTS_data", branch = "master")

##  Get the gridded data locally
bt_data <- pins::pin_get("bt-traitfiltered", board = "github") %>%
  rename_with(tolower)

trait_ref <- pins::pin_get("trait-ref", board = "github")

bt_abund <- bt_data %>%
  filter(abundance_type %in% c("Count", "Density", "MeanCount"))

bt_pres <- bt_data %>%
  filter(abundance_type == "Presence/Absence")
loadRData <- function(file_name){
  load(file_name)
  get(ls()[ls() != "file_name"])
}

get_ts_distinct <- function(file_path, trait_data){

  rare_comm_save <- loadRData(file_path)

  species_mat <- rare_comm_save %>%
    column_to_rownames("YEAR") %>%
    dplyr::select(-c(rarefyID, cell, type, rarefy_resamp))

  rel_species <- make_relative(as.matrix(species_mat))

  trait_dist <- get_traitMat(colnames(species_mat), trait_data)

  trait_dist <- trait_dist %>%
    mutate_if(is.character, as.factor) %>%
    compute_dist_matrix(., metric = "gower")

  distinctive <- as.data.frame(distinctiveness(pres_matrix = rel_species, dist_matrix = trait_dist)) %>%
    rownames_to_column("year") %>%
    mutate(rarefyid = unique(rare_comm_save$rarefyID), 
           rarefy_resamp = unique(rare_comm_save$rarefy_resamp))

  return(distinctive)
}


path <- here::here("data", "rarefied_samples")
files <- dir(path, "*.rda") %>%
  paste0(path, "/", .)

plan("multiprocess", workers = 120)
yearly_distinct <- furrr::future_map_dfr(files, get_ts_distinct, trait_data = trait_ref) %>%
  pivot_longer(starts_with("ITIS:"), names_to = "species", values_to = "distinctiveness") %>%
  filter(!is.na(distinctiveness))

Get species-pool level classifications of distinctiveness/scarcity

sp_data <- bt_data %>%
  select(species, rarefyid, abundance, abundance_type)

## Break data down into different kinds of observations to aggregate across years
# first presence/absence
presence_sp <- sp_data %>%
  filter(abundance_type == "Presence/Absence") %>%
  select(species, rarefyid) %>%
  distinct() %>%
  mutate(abundance = 1)

# and then things that act like counts
count_sp <- sp_data %>%
  filter(abundance_type != "Presence/Absence") %>%
  group_by(rarefyid, species, abundance_type) %>%
  mutate(abundance = sum(abundance))


karinorman/biodivTS documentation built on Dec. 23, 2024, 10 p.m.