Last updated: 2021-12-30

Checks: 7 0

Knit directory: ms_mariposas_biodiversity/

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(20211228) 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 ec59e79. 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/

Untracked files:
    Untracked:  analysis/plot_variables_elevation.Rmd
    Untracked:  data/densidad_by_year.csv
    Untracked:  data/diversidad_by_year.csv
    Untracked:  data/longitud_transectos.xlsx
    Untracked:  data/mariposas_diurnas_contactos_transectos.csv
    Untracked:  data/mariposas_diurnas_visitas.csv
    Untracked:  data/riqueza_by_year.csv
    Untracked:  data/transect_abrev.csv
    Untracked:  figs/

Unstaged changes:
    Modified:   analysis/index.Rmd
    Modified:   data/Mariposas_2008_2021.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/prepara_datos_mariposas.Rmd) and HTML (docs/prepara_datos_mariposas.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 ec59e79 ajpelu 2021-12-30 Generate script of prepara datos


En este apartado usamos los datos de contactos de mariposas para su preparación.


Preparación de datos

  • Usamos datos descargados directamente de Tenemos dos archivos: conteos y visitas.

  • Utilizamos solo fecha de inicio y computamos mes, año y día de cada contacto.

  • Filtramos los datos:

    • No utilizaremos los años 2008, 2009, 2010, 2011, 2021
    • No utilizaremos datos de los meses de marzo, abril, septiembre y octubre
rawdata <- read_delim(here::here("data/mariposas_diurnas_contactos_transectos.csv"), delim = ";") %>% 
  janitor::clean_names() %>% 
  mutate(year = lubridate::year(fecha_inicio), 
         month = lubridate::month(fecha_inicio), 
         day = lubridate::day(fecha_inicio)) %>% 
  dplyr::select(-fecha_fin, -fecha_inicio)
d <- rawdata %>%
  filter(year >= 2011) %>% 
  filter(year < 2021) %>% 
  filter(!(month %in% c(3,4,9,10)))
  • Leer información de transectos: longitud, abreviatura; y creamos una variable llamada elev (elevación) que corresponde al promedio entre la altura mínima y máxima del transecto.
metadata_transectos <- read_excel(here::here("data/longitud_transectos.xlsx"),
                 sheet = "Longitud_transectos") %>% 
  janitor::clean_names() %>% 
  mutate(id_transecto = paste0("16_",transectid))

abrev <- read_csv(here::here("data/transect_abrev.csv")) %>% janitor::clean_names() %>% 
  rename(id_transecto = id_transect)

transectos <- metadata_transectos %>% 
  inner_join(abrev) %>% 
  dplyr::select(-transectid, -transect) %>% 
  rowwise() %>% 
  mutate(elev = round(((min_altitu+max_altitu)/2),0)) %>% 
  rename(transecto = name)

Total contactos transecto y año

  • Generamos un dataset con el total (número de contactos) por transecto y visita
ntotal_transecto_visita <- d %>% 
  group_by(id_visita, id_transecto, transecto, year) %>% 
  summarise(ntotal = sum(total)) 
  • Leemos información de las visitas realizadas a los transectos. Genero un dataset de visitas con aquellas visitas sin contactos
rawvisitas <- read_delim(here::here("data/mariposas_diurnas_visitas.csv"), 
                      delim = ";", col_types = cols(Temperatura = col_number())) %>% janitor::clean_names() %>% 
    mutate(year = lubridate::year(fecha_inicio), 
         month = lubridate::month(fecha_inicio), 
         day = lubridate::day(fecha_inicio)) %>%
  dplyr::select(-fecha_fin, -fecha_inicio)
visitas <- rawvisitas %>%
  filter(year >= 2011) %>% 
  filter(year < 2021) %>% 
  filter(!(month %in% c(3,4,9,10))) %>% 
  dplyr::select(id_visita=id, transecto=transecto_parcela, year, month, day) 

ntotal_transecto_visitas_cero <- visitas %>% 
  filter(!(id_visita %in% unique(d$id_visita))) %>% 
  mutate(ntotal = 0) %>% 
  dplyr::select(-month, -day) %>% 
  inner_join((transectos %>% dplyr::select(transecto, id_transecto))) %>% 
  relocate(id_visita, transecto, id_transecto)
  • Unimos los dos datasets anteriores y le adjuntamos información de los transectos.

  • Filtramos los datos de 2018. Eliminamos todas las visitas de 2018 excepto para los transectos Pitres, Dúrcal, Turbera, Laguna (“16_45”,“16_46”,“16_48”,“16_49”)

ntotalraw <- bind_rows(ntotal_transecto_visita, ntotal_transecto_visitas_cero) %>% inner_join(transectos) 

ntotal <- ntotalraw %>% 
  filter(!(year == 2018 & !id_transecto %in% c("16_45","16_46","16_48","16_49")))


  • Densidad por año
densidad_by_year <- ntotal %>% 
  group_by(id_transecto, transecto, site, elev, year) %>% 
  summarise(abundancia = sum(ntotal), 
         long_total = sum(longitud) / 100) %>% 
  mutate(den = abundancia / long_total)
write_csv(densidad_by_year, here::here("data/densidad_by_year.csv"))


  • ¿Cuantas especies se han contactado?. Observamos que hay registros de taxones identificados a diferentes niveles. Vamos a ver aquellos que estén registrados a nivel al menos específico.
taxones_anotados <- d %>% 
  dplyr::select(id_especie, nombre_cientifico) %>% unique() %>% 
  mutate(w = stringr::str_count(nombre_cientifico, "\\w+"))

especies <- taxones_anotados %>% filter(w>1)
m <- d %>% 
  filter(!(year == 2018 & !id_transecto %in% c("16_45","16_46","16_48","16_49"))) %>% 
  filter(nombre_cientifico %in% especies$nombre_cientifico) %>% 
  mutate(sp = stringr::word(nombre_cientifico, start = 1, end = 2)) %>% 
  mutate(spabrev = stringr::str_replace(sp," ", ".")) %>% 
  dplyr::select(-sp) %>% 
  mutate(sp = str_replace(spabrev, " ", ".")) %>% 
  group_by(transecto, spabrev, year) %>% 
  summarise(n_ind = sum(total)) %>% 
  pivot_wider(names_from = year, 
              names_prefix = "y", values_fill = 0) %>%

years <- c("y2012","y2013","y2014","y2015","y2016","y2017","y2018","y2019","y2020")

out_h <- data.frame() 
for (y in years){ 
  vars <- c("spabrev", "transecto", y) 
  aux_diversidad <- m %>% 
    dplyr::select(all_of(vars)) %>% 
    pivot_wider(names_from = spabrev, values_from = y, values_fill = 0) %>% 
    column_to_rownames(var = "transecto")
  h <- vegan::diversity(aux_diversidad) %>%
  names(h) <- "diversidad"
  h$year <- y
  h$transecto <- row.names(h)
  out_h <- rbind(out_h, h)

# Ojo en el cómputo de diversidad aparecen años y transectos con 0. Creo que es un error. Los dejo con NA 

rownames(out_h) <- NULL 
diversidad <- out_h %>% 
  mutate(year = as.numeric(substring(year,2)),
         diversidad = na_if(diversidad,0)) %>% 

write_csv(diversidad, here::here("data/diversidad_by_year.csv"))


riq <- d %>% 
  filter(!(year == 2018 & !id_transecto %in% c("16_45","16_46","16_48","16_49"))) %>% 
  filter(nombre_cientifico %in% especies$nombre_cientifico) %>% 
  mutate(sp = stringr::word(nombre_cientifico, start = 1, end = 2)) %>% 
  mutate(spabrev = stringr::str_replace(sp," ", ".")) %>% 
  dplyr::select(-sp) %>%
  group_by(transecto, year) %>% 
  summarise(sp_unique = unique(spabrev)) %>% 
  group_by(transecto, year) %>% 
  count() %>% 
  rename(riq = n) %>% 

write_csv(riq, here::here("data/riqueza_by_year.csv"))

R version 4.0.2 (2020-06-22)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Catalina 10.15.3

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

[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] vegan_2.5-7      lattice_0.20-41  permute_0.9-5    DT_0.17         
 [5] lubridate_1.7.10 here_1.0.1       janitor_2.1.0    readxl_1.3.1    
 [9] forcats_0.5.1    stringr_1.4.0    dplyr_1.0.6      purrr_0.3.4     
[13] readr_1.4.0      tidyr_1.1.3      tibble_3.1.2     ggplot2_3.3.5   
[17] tidyverse_1.3.1  workflowr_1.7.0 

loaded via a namespace (and not attached):
 [1] httr_1.4.2        sass_0.3.1        splines_4.0.2     jsonlite_1.7.2   
 [5] modelr_0.1.8      bslib_0.2.4       assertthat_0.2.1  getPass_0.2-2    
 [9] cellranger_1.1.0  yaml_2.2.1        pillar_1.6.1      backports_1.2.1  
[13] glue_1.4.2        digest_0.6.27     promises_1.2.0.1  rvest_1.0.0      
[17] snakecase_0.11.0  colorspace_2.0-2  Matrix_1.3-2      htmltools_0.5.2  
[21] httpuv_1.5.5      pkgconfig_2.0.3   broom_0.7.9       haven_2.3.1      
[25] scales_1.1.1.9000 processx_3.5.1    whisker_0.4       later_1.1.0.1    
[29] git2r_0.28.0      mgcv_1.8-33       generics_0.1.0    ellipsis_0.3.2   
[33] withr_2.4.1       cli_2.5.0         magrittr_2.0.1    crayon_1.4.1     
[37] evaluate_0.14     ps_1.5.0          fs_1.5.0          fansi_0.4.2      
[41] nlme_3.1-152      MASS_7.3-53       xml2_1.3.2        tools_4.0.2      
[45] hms_1.0.0         lifecycle_1.0.1   munsell_0.5.0     reprex_2.0.0     
[49] cluster_2.1.0     callr_3.7.0       compiler_4.0.2    jquerylib_0.1.3  
[53] rlang_0.4.12      grid_4.0.2        rstudioapi_0.13   htmlwidgets_1.5.3
[57] crosstalk_1.1.1   rmarkdown_2.8     gtable_0.3.0      DBI_1.1.1        
[61] R6_2.5.1          knitr_1.31        fastmap_1.1.0     utf8_1.1.4       
[65] rprojroot_2.0.2   stringi_1.7.4     parallel_4.0.2    Rcpp_1.0.7       
[69] vctrs_0.3.8       dbplyr_2.1.1      tidyselect_1.1.1  xfun_0.23