Last updated: 2023-08-21

Checks: 7 0

Knit directory: ms_mariposas_pheno/

This reproducible R Markdown analysis was created with workflowr (version 1.7.0). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20230601) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version effd2e0. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .Rhistory
    Ignored:    .Rproj.user/
    Ignored:    data/.DS_Store
    Ignored:    data/raw_data/.DS_Store

Unstaged changes:
    Modified:   analysis/model_selection.Rmd
    Modified:   data/best_models_prec.csv
    Modified:   data/best_models_prec.xlsx
    Modified:   data/best_models_temp.csv
    Modified:   data/best_models_temp.xlsx
    Modified:   data/doy_medio_sp.xlsx
    Modified:   data/models_prec.csv
    Modified:   data/models_prec.xlsx
    Modified:   data/models_prec_scaled.xlsx
    Modified:   data/models_tmed.csv
    Modified:   data/models_tmed.xlsx
    Modified:   data/models_tmed_scaled.xlsx

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the repository in which changes were made to the R Markdown (analysis/climate_sensibility.Rmd) and HTML (docs/climate_sensibility.html) files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view the files as they were in that past version.

File Version Author Date Message
Rmd effd2e0 ajpelu 2023-08-21 fix error with best models
html 9c3ec4e ajpelu 2023-08-21 Build site.
Rmd 12a5db3 ajpelu 2023-08-21 update climate sensibilituy
html 6c5da5b ajpelu 2023-07-26 Build site.
Rmd 20aeb79 ajpelu 2023-07-26 climate sensibility
Rmd 0bb952a ajpelu 2023-07-11 update climate sensibility
Rmd c97d62e ajpelu 2023-06-28 add new data

Introduction

library(tidyverse)
library(here)
library(vroom)
library(glue)
library(glmulti)
library(lme4)
library(broom)
library(broom.mixed)
library(kableExtra)
library(DT)
library(qpcR)
df_doy_wmd <- vroom::vroom(here::here("data/doy_peak_sps_WMD.csv"))
transectos <- vroom::vroom(here::here("data/transectos_metadata.csv"))

climate_data <- vroom::vroom(here::here("data/transectos_climate.csv")) |> 
  filter(hydro_year !=2007) |> 
  rename(site_id = transectid, year = hydro_year)

Prepare data

# aux_df <- df_doy |> 
#   filter(species %in% selected_sps$sp) |> 
#   dplyr::select(species, year, doy, site_id) 

aux_df <- df_doy_wmd |> 
   # filter(species %in% selected_sps$sp) |> 
   dplyr::select(species, year, doy = weigth_mean_date, site_id) 

df_tmean <- aux_df |> 
  left_join(
    (climate_data |> filter(var == "tmed")))

df_prec <- aux_df |> 
  inner_join(
    (climate_data |> filter(var == "p")))

Models

  • For each species, we model the relationship between the flight’s peak doy and the temperature (and precipitation) variables.
  • We built 36 models using a time-window approach. We calculated the mean temperatures (and cumulative precipitation) of 36 potential time-windows ranging from one to three months from October of the previous year to September of the current year.
  • We used these potential time-windows to identify the period of the year with the highest temperature (or precipitation) effect on the phenology of each species (the critical period).
  • For each time-window and species, we fitted the DOY using a model with temperature (or precipitation) as a predictor. Two types of model were used: for those species with more than 1 site, we fitted a GLMM model with site as a random effect and a Gaussian error distribution; and for species with only a site, we fitted a GLM with Gaussian error distribution.
  • For each species, we selected the best-fit model according to the AIC.
  • We compute the models with two approach: scaled a non-scaled. The first one were computed to get the slopes and compare the sensibility to temperature and precipitation.

Temperature med

Scaled models

fit_glmm <- function(df, x) {
  glmm <- lme4::glmer(scale(doy) ~ scale(x) + (1 | site_id), 
                family = gaussian, 
                data = df)
  return(glmm)
}


fit_glm <- function(df, x) { 
  glm <- glm(scale(doy) ~ scale(x), 
                family = gaussian, 
                data = df)
  return(glm)
  }

sps <- unique(df_doy_wmd$species)

models_tmed<- data.frame()

# Tmed 
for (i in sps) {
  df <-
    df_doy_wmd |>
    filter(species == i) |>
    # dplyr::select(species, year, doy, site_id) |>
    dplyr::select(species, year, doy = weigth_mean_date, site_id) |>
    left_join(climate_data |> filter(var == "tmed"))


  nsites <- length(unique(df$site_id))

  if (nsites <= 1) {
    models <- df |>
      dplyr::select(Jan:Dec_preJanFeb) |>
      map(~ fit_glm(df, .x))

    # get AIC
    models_aic <- map(models, broom::glance) |>
      bind_rows(.id = "Model")
    
    # get R2
    models_r <- map2_dfr(
      names(models), models,
      ~ data.frame(Model = .x, r2 = MuMIn::r.squaredLR(.y))
    )
    
    # get COEF
    models_coef <- map(models, ~ broom::tidy(.x, conf.level = 0.95)) |>
      bind_rows(.id = "Model") |>
      rename(p_value = p.value)

    output_models <- models_coef |>
      full_join(models_aic, multiple = "all") |>
      full_join(models_r, multiple = "all") |>
      arrange(AIC) |>
      mutate(species = i, 
             model_type = "no mixed",
             nsites = nsites) |>
      relocate(species, nsites, model_type) 

    models_tmed <- bind_rows(models_tmed, output_models)
    
  } else {
    # if (nrow(df) > 5) {

    models <- df |>
      dplyr::select(Jan:Dec_preJanFeb) |>
      map(~ fit_glmm(df, .x))

    # get AIC
    models_aic <- map(models, broom.mixed::glance) |>
      bind_rows(.id = "Model")

    # get R2
    models_r <- map2_dfr(
      names(models), models,
      ~ data.frame(Model = .x, r2 = MuMIn::r.squaredGLMM(.y))
    )

    # get COEF
    models_coef <- map(models, ~ broom.mixed::tidy(.x,
      effects = c("fixed"),
      conf.level = 0.95
    )) |>
      bind_rows(.id = "Model") |>
      mutate(p_value = round(2 * (1 - pnorm(abs(statistic))), 4)) # add p.value of coef

    output_models <- models_coef |>
      full_join(models_aic, multiple = "all") |>
      full_join(models_r, multiple = "all") |>
      arrange(AIC) |>
      mutate(species = i, 
             model_type = "mixed",
             nsites = nsites) |>
      relocate(species, nsites, model_type) 

    models_tmed <- bind_rows(models_tmed, output_models)
  }
}

How many species

length(unique(models_tmed$species))
[1] 36
models_tmed |>
  mutate(across(c(estimate, std.error, statistic, sigma, logLik, AIC, BIC, REMLcrit), ~round(., digits = 3))) |> 
  mutate(across(c(r2.R2m, r2.R2c, r2), ~round(., digits = 3))) |> 
  mutate(across(c(p_value), ~round(., digits = 4))) |> 
  DT::datatable()
write_csv(models_tmed, "data/models_tmed_scaled.csv")
writexl::write_xlsx(models_tmed, "data/models_tmed_scaled.xlsx")

Non-scaled models

fit_glmm <- function(df, x) {
  glmm <- lme4::glmer(doy ~ x + (1 | site_id), 
                family = gaussian, 
                data = df)
  return(glmm)
}

fit_glm <- function(df, x) { 
  glm <- glm(doy ~ x, 
                family = gaussian, 
                data = df)
  return(glm)
  }

sps <- unique(df_doy_wmd$species)

models_tmed<- data.frame()

# Tmed 
for (i in sps) { 
  df <-
    df_doy_wmd |>
    filter(species == i) |>
    dplyr::select(species, year, doy = weigth_mean_date, site_id) |>
    left_join(climate_data |> filter(var == "tmed"))
  
  nsites <- length(unique(df$site_id))

  if (nsites <= 1) {
    models <- df |>
      dplyr::select(Jan:Dec_preJanFeb) |>
      map(~ fit_glm(df, .x))

    # get AIC
    models_aic <- map(models, broom::glance) |>
      bind_rows(.id = "Model")
    
    # get R2
    models_r <- map2_dfr(
      names(models), models,
      ~ data.frame(Model = .x, r2 = MuMIn::r.squaredLR(.y))
    )
    
    # get COEF
    models_coef <- map(models, ~ broom::tidy(.x, conf.level = 0.95)) |>
      bind_rows(.id = "Model") |>
      rename(p_value = p.value)

    output_models <- models_coef |>
      full_join(models_aic, multiple = "all") |>
      full_join(models_r, multiple = "all") |>
      arrange(AIC) |>
      mutate(species = i, 
             model_type = "no mixed",
             nsites = nsites) |>
      relocate(species, nsites, model_type) 

    models_tmed <- bind_rows(models_tmed, output_models)
    
  } else { 
    models <- df |>
      dplyr::select(Jan:Dec_preJanFeb) |>
      map(~ fit_glmm(df, .x))

    # get AIC
    models_aic <- map(models, broom.mixed::glance) |>
      bind_rows(.id = "Model")

    # get R2
    models_r <- map2_dfr(
      names(models), models,
      ~ data.frame(Model = .x, r2 = MuMIn::r.squaredGLMM(.y))
    )

    # get COEF
    models_coef <- map(models, ~ broom.mixed::tidy(.x,
      effects = c("fixed"),
      conf.level = 0.95
    )) |>
      bind_rows(.id = "Model") |>
      mutate(p_value = round(2 * (1 - pnorm(abs(statistic))), 4)) # add p.value of coef

    output_models <- models_coef |>
      full_join(models_aic, multiple = "all") |>
      full_join(models_r, multiple = "all") |>
      arrange(AIC) |>
      mutate(species = i, 
             model_type = "mixed",
             nsites = nsites) |>
      relocate(species, nsites, model_type) 

    models_tmed <- bind_rows(models_tmed, output_models)
    }
}

How many species

length(unique(models_tmed$species))
[1] 36
models_tmed |>
  mutate(across(c(estimate, std.error, statistic, sigma, logLik, AIC, BIC, REMLcrit), ~round(., digits = 3))) |> 
  mutate(across(c(r2.R2m, r2.R2c, r2), ~round(., digits = 3))) |> 
  mutate(across(c(p_value), ~round(., digits = 4))) |> 
  DT::datatable()
write_csv(models_tmed, "data/models_tmed.csv")
writexl::write_xlsx(models_tmed, "data/models_tmed.xlsx")

Precip

Scaled models

fit_glmm <- function(df, x) {
  glmm <- lme4::glmer(scale(doy) ~ scale(x) + (1 | site_id), 
                family = gaussian, 
                data = df)
  return(glmm)
}

fit_glm <- function(df, x) { 
  glm <- glm(scale(doy) ~ scale(x), 
                family = gaussian, 
                data = df)
  return(glm)
  }

sps <- unique(df_doy_wmd$species)

models_prec <- data.frame()

# Prec 
for (i in sps) { 
  df <-
    df_doy_wmd |>
    filter(species == i) |>
    dplyr::select(species, year, doy = weigth_mean_date, site_id) |>
    left_join(climate_data |> filter(var == "p"))
  
  nsites <- length(unique(df$site_id))

  if (nsites <= 1) { 
    models <- df |>
      dplyr::select(Jan:Dec_preJanFeb) |>
      map(~ fit_glm(df, .x))

    # get AIC
    models_aic <- map(models, broom::glance) |>
      bind_rows(.id = "Model")
    
    # get R2
    models_r <- map2_dfr(
      names(models), models,
      ~ data.frame(Model = .x, r2 = MuMIn::r.squaredLR(.y))
    )
    
    # get COEF
    models_coef <- map(models, ~ broom::tidy(.x, conf.level = 0.95)) |>
      bind_rows(.id = "Model") |>
      rename(p_value = p.value)

    output_models <- models_coef |>
      full_join(models_aic, multiple = "all") |>
      full_join(models_r, multiple = "all") |>
      arrange(AIC) |>
      mutate(species = i, 
             model_type = "no mixed",
             nsites = nsites) |>
      relocate(species, nsites, model_type) 

    models_prec <- bind_rows(models_prec, output_models)
    
  } else {

  models <- df |>
      dplyr::select(Jan:Dec_preJanFeb) |>
      map(~ fit_glmm(df, .x))

    # get AIC
    models_aic <- map(models, broom.mixed::glance) |>
      bind_rows(.id = "Model")

    # get R2
    models_r <- map2_dfr(
      names(models), models,
      ~ data.frame(Model = .x, r2 = MuMIn::r.squaredGLMM(.y))
    )

    # get COEF
    models_coef <- map(models, ~ broom.mixed::tidy(.x,
      effects = c("fixed"),
      conf.level = 0.95
    )) |>
      bind_rows(.id = "Model") |>
      mutate(p_value = round(2 * (1 - pnorm(abs(statistic))), 4)) # add p.value of coef

    output_models <- models_coef |>
      full_join(models_aic, multiple = "all") |>
      full_join(models_r, multiple = "all") |>
      arrange(AIC) |>
      mutate(species = i, 
             model_type = "mixed",
             nsites = nsites) |>
      relocate(species, nsites, model_type) 
  
  models_prec <- bind_rows(models_prec, output_models)
     
  }
}

How many species

length(unique(models_prec$species))
[1] 36
models_prec |>
  mutate(across(c(estimate, std.error, statistic, sigma, logLik, AIC, BIC, REMLcrit), ~round(., digits = 3))) |> 
  mutate(across(c(r2.R2m, r2.R2c, r2), ~round(., digits = 3))) |> 
  mutate(across(c(p_value), ~round(., digits = 4))) |> 
  DT::datatable()
write_csv(models_prec, "data/models_prec_scaled.csv")
writexl::write_xlsx(models_prec, "data/models_prec_scaled.xlsx")

Non-scaled models

fit_glmm <- function(df, x) {
  glmm <- lme4::glmer(doy ~ x + (1 | site_id), 
                family = gaussian, 
                data = df)
  return(glmm)
}

fit_glm <- function(df, x) { 
  glm <- glm(doy ~ x, 
                family = gaussian, 
                data = df)
  return(glm)
  }

sps <- unique(df_doy_wmd$species)

models_prec <- data.frame()

# Prec 
for (i in sps) { 
  df <-
    df_doy_wmd |>
    filter(species == i) |>
    dplyr::select(species, year, doy = weigth_mean_date, site_id) |>
    left_join(climate_data |> filter(var == "p"))
  
  nsites <- length(unique(df$site_id))

  if (nsites <= 1) { 
    models <- df |>
      dplyr::select(Jan:Dec_preJanFeb) |>
      map(~ fit_glm(df, .x))

    # get AIC
    models_aic <- map(models, broom::glance) |>
      bind_rows(.id = "Model")
    
    # get R2
    models_r <- map2_dfr(
      names(models), models,
      ~ data.frame(Model = .x, r2 = MuMIn::r.squaredLR(.y))
    )
    
    # get COEF
    models_coef <- map(models, ~ broom::tidy(.x, conf.level = 0.95)) |>
      bind_rows(.id = "Model") |>
      rename(p_value = p.value)

    output_models <- models_coef |>
      full_join(models_aic, multiple = "all") |>
      full_join(models_r, multiple = "all") |>
      arrange(AIC) |>
      mutate(species = i, 
             model_type = "no mixed",
             nsites = nsites) |>
      relocate(species, nsites, model_type) 

    models_prec <- bind_rows(models_prec, output_models)
    
  } else {

  models <- df |>
      dplyr::select(Jan:Dec_preJanFeb) |>
      map(~ fit_glmm(df, .x))

    # get AIC
    models_aic <- map(models, broom.mixed::glance) |>
      bind_rows(.id = "Model")

    # get R2
    models_r <- map2_dfr(
      names(models), models,
      ~ data.frame(Model = .x, r2 = MuMIn::r.squaredGLMM(.y))
    )

    # get COEF
    models_coef <- map(models, ~ broom.mixed::tidy(.x,
      effects = c("fixed"),
      conf.level = 0.95
    )) |>
      bind_rows(.id = "Model") |>
      mutate(p_value = round(2 * (1 - pnorm(abs(statistic))), 4)) # add p.value of coef

    output_models <- models_coef |>
      full_join(models_aic, multiple = "all") |>
      full_join(models_r, multiple = "all") |>
      arrange(AIC) |>
      mutate(species = i, 
             model_type = "mixed",
             nsites = nsites) |>
      relocate(species, nsites, model_type) 
  
  models_prec <- bind_rows(models_prec, output_models)
     
  }
}

How many species

length(unique(models_prec$species))
[1] 36
models_prec |>
  mutate(across(c(estimate, std.error, statistic, sigma, logLik, AIC, BIC, REMLcrit), ~round(., digits = 3))) |> 
  mutate(across(c(r2.R2m, r2.R2c, r2), ~round(., digits = 3))) |> 
  mutate(across(c(p_value), ~round(., digits = 4))) |> 
  DT::datatable()
write_csv(models_prec, "data/models_prec.csv")
writexl::write_xlsx(models_prec, "data/models_prec.xlsx")

Select best models for each species

best_models_temp <- models_tmed |> 
  group_by(species) |> 
  filter(term == "x") |> 
  dplyr::select(species, Model, AIC) |> 
  mutate(deltaAIC = akaike.weights(AIC)$deltaAIC, 
         w = akaike.weights(AIC)$weights) |> 
  filter(deltaAIC <= 4)

write_csv(best_models_temp, "data/best_models_temp.csv")
writexl::write_xlsx(best_models_temp, "data/best_models_temp.xlsx")


best_models_prec <- models_prec |> 
  group_by(species) |> 
  filter(term == "x") |> 
  dplyr::select(species, Model, AIC) |> 
  mutate(deltaAIC = akaike.weights(AIC)$deltaAIC, 
         w = akaike.weights(AIC)$weights) |> 
  filter(deltaAIC <= 4)

write_csv(best_models_prec, "data/best_models_prec.csv")
writexl::write_xlsx(best_models_prec, "data/best_models_prec.xlsx")
doy_medio_sp <- df_doy_wmd |> 
  group_by(species) |> 
  summarise(doym = as.Date( mean(weigth_mean_date),origin = as.Date("2024-01-01")))

write_csv(doy_medio_sp, "data/doy_medio_sp.csv")
writexl::write_xlsx(doy_medio_sp, "data/doy_medio_sp.xlsx")

sessionInfo()
R version 4.2.3 (2023-03-15)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Big Sur ... 10.16

Matrix products: default
BLAS:   /Library/Frameworks/R.framework/Versions/4.2/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.2/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] qpcR_1.4-1          robustbase_0.95-0   rgl_0.110.2        
 [4] minpack.lm_1.2-3    MASS_7.3-58.2       DT_0.26            
 [7] kableExtra_1.3.4    broom.mixed_0.2.9.4 broom_1.0.4        
[10] lme4_1.1-30         Matrix_1.5-3        glmulti_1.0.8      
[13] leaps_3.1           rJava_1.0-6         glue_1.6.2         
[16] vroom_1.6.3         here_1.0.1          lubridate_1.9.2    
[19] forcats_1.0.0       stringr_1.5.0       dplyr_1.1.0        
[22] purrr_1.0.1         readr_2.1.4         tidyr_1.3.0        
[25] tibble_3.1.8        ggplot2_3.4.1       tidyverse_2.0.0    
[28] workflowr_1.7.0    

loaded via a namespace (and not attached):
 [1] nlme_3.1-162      fs_1.6.2          bit64_4.0.5       webshot_0.5.4    
 [5] httr_1.4.4        rprojroot_2.0.3   tools_4.2.3       backports_1.4.1  
 [9] bslib_0.4.2       utf8_1.2.2        R6_2.5.1          colorspace_2.0-3 
[13] withr_2.5.0       tidyselect_1.2.0  processx_3.7.0    bit_4.0.4        
[17] compiler_4.2.3    git2r_0.30.1      cli_3.6.0         rvest_1.0.3      
[21] xml2_1.3.3        sass_0.4.5        scales_1.2.1      DEoptimR_1.0-11  
[25] callr_3.7.3       systemfonts_1.0.4 digest_0.6.31     minqa_1.2.4      
[29] rmarkdown_2.19    svglite_2.1.0     MuMIn_1.47.1      base64enc_0.1-3  
[33] pkgconfig_2.0.3   htmltools_0.5.4   parallelly_1.32.1 fastmap_1.1.0    
[37] htmlwidgets_1.6.2 rlang_1.1.0       rstudioapi_0.14   jquerylib_0.1.4  
[41] generics_0.1.3    jsonlite_1.8.4    crosstalk_1.2.0   magrittr_2.0.3   
[45] Rcpp_1.0.10       munsell_0.5.0     fansi_1.0.3       lifecycle_1.0.3  
[49] furrr_0.3.1       stringi_1.7.8     whisker_0.4       yaml_2.3.7       
[53] grid_4.2.3        parallel_4.2.3    listenv_0.8.0     promises_1.2.0.1 
[57] crayon_1.5.2      lattice_0.20-45   splines_4.2.3     hms_1.1.2        
[61] knitr_1.41        ps_1.7.1          pillar_1.8.1      boot_1.3-28.1    
[65] stats4_4.2.3      codetools_0.2-19  evaluate_0.19     getPass_0.2-2    
[69] vctrs_0.6.0       nloptr_2.0.3      tzdb_0.3.0        httpuv_1.6.8     
[73] gtable_0.3.1      future_1.28.0     cachem_1.0.6      xfun_0.39        
[77] later_1.3.0       viridisLite_0.4.1 writexl_1.4.2     timechange_0.1.1 
[81] globals_0.16.1    ellipsis_0.3.2