## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  eval = F,
  warning = FALSE
)

## ----eval=T, echo=F, fig.align='center', out.width='80%', fig.cap="Araucaria forest in southern Brazil"----
knitr::include_graphics("vignettes_img/paranapine2.jpeg")

## ----eval = T-----------------------------------------------------------------
# Load RuHere package
library(RuHere)

## -----------------------------------------------------------------------------
# set_gbif_credentials(
#   gbif_username = "your_username",
#   gbif_email = "your_email@domain.com",
#   gbif_password = "your_password",
#   verbose = FALSE
# )

## -----------------------------------------------------------------------------
# set_specieslink_credentials(specieslink_key = "your_api_key", verbose = FALSE)

## -----------------------------------------------------------------------------
# # Store downloads in a temporary directory
# # In your own project, replace this with a permanent directory
# output_dir <- file.path(tempdir(), "occ_data")
# dir.create(output_dir)

## -----------------------------------------------------------------------------
# # Prepare the taxonomic query
# gbif_prep <- prepare_gbif_download(species = "Araucaria angustifolia")

## -----------------------------------------------------------------------------
# gbif_prep
# #> with_coordinates n_records                species usageKey                          scientificName          canonicalName
# #> 1             3056     15696 Araucaria angustifolia  2684940 Araucaria angustifolia (Bertol.) Kuntze Araucaria angustifolia
# #>     rank   status confidence matchType kingdom       phylum   order        family     genus kingdomKey phylumKey classKey
# #> 1 SPECIES ACCEPTED         97     EXACT Plantae Tracheophyta Pinales Araucariaceae Araucaria          6   7707728      194
# #>   orderKey familyKey genusKey speciesKey     class          verbatim_name
# #> 1      640      3924  2684910    2684940 Pinopsida Araucaria angustifolia

## -----------------------------------------------------------------------------
# # Submit the request to GBIF
# gbif_req <- request_gbif(
#   gbif_info = gbif_prep,
#   hasCoordinate = TRUE,      # Retrieve only records with coordinates
#   hasGeospatialIssue = FALSE # Exclude records with geospatial issues
# )

## -----------------------------------------------------------------------------
# rgbif::occ_download_wait(gbif_req)
# #> status: succeeded
# #> download is done, status: succeeded

## -----------------------------------------------------------------------------
# # Import the processed file
# occ_gbif <- import_gbif(request_key = gbif_req)
# #> Download file size: 2.04 MB

## -----------------------------------------------------------------------------
# head(occ_gbif)
# #> # A tibble: 6 × 25
# #>   scientificName                acceptedScientificName occurrenceID collectionCode catalogNumber decimalLongitude #> decimalLatitude
# #>   <chr>                         <chr>                  <chr>        <chr>          <chr>                    <dbl>           #> <dbl>
# #> 1 Araucaria angustifolia (Bert… Araucaria angustifoli… urn:catalog… ALTA-VP        74703                    -52.8          #> -26.4
# #> 2 Araucaria angustifolia (Bert… Araucaria angustifoli… https://www… Observations   329390275                -49.2          #> -25.4
# #> 3 Araucaria angustifolia (Bert… Araucaria angustifoli… https://www… Observations   329483122                -49.5          #> -28.0
# #> 4 Araucaria angustifolia (Bert… Araucaria angustifoli… https://www… Observations   329455309                -74.0            #> 4.68
# #> 5 Araucaria angustifolia (Bert… Araucaria angustifoli… https://www… Observations   329576016                -45.6          #> -22.7
# #> 6 Araucaria angustifolia (Bert… Araucaria angustifoli… https://www… Observations   329805643                175.           #> -39.9
# #> # ℹ 18 more variables: coordinateUncertaintyInMeters <dbl>, elevation <dbl>, continent <chr>, countryCode <chr>,
# #> #   stateProvince <chr>, municipality <chr>, locality <chr>, verbatimLocality <chr>, year <int>, eventDate <chr>,
# #> #   recordedBy <chr>, identifiedBy <chr>, basisOfRecord <chr>, occurrenceRemarks <chr>, habitat <chr>, datasetName <chr>,
# #> #   datasetKey <chr>, speciesKey <int>

## -----------------------------------------------------------------------------
# rgbif::gbif_citation(gbif_req[1])
# #> $download
# #> [1] GBIF Occurrence Download https://doi.org/10.15468/dl.wdcvz4 Accessed from R via rgbif (https://github.com/ropensci/rgbif) on 2026-01-27"
# #>
# #> $datasets
# #> NULL

## -----------------------------------------------------------------------------
# # SpeciesLink: Filtering by Species
# occ_sl <- get_specieslink(species = "Araucaria angustifolia", verbose = FALSE)
# 
# # BIEN: Natives only, excluding cultivated records
# occ_bien <- get_bien(species = "Araucaria angustifolia",
#                      cultivated = FALSE,
#                      natives.only = TRUE,
#                      verbose = FALSE)
# #> Getting page 1 of records
# 
# # iDigBio:
# occ_idig <- get_idigbio(species = "Araucaria angustifolia")

## -----------------------------------------------------------------------------
# dp <- get_datapaper(datapaper = c("atlantic", "dryflor"))
# #> Downloading data from atlantic datapapers...
# #> Downloading data from DryFlor...
# #> Datapaper(s) successfully retrieved.
# #>
# #> ##########################################################################
# #>   PLEASE, USE THE FUNCTION cite_datapaper() TO CITE DATAPAPERS RETRIEVED
# #> ##########################################################################
# 
# # Check the number of records retrieved per dataset
# table(dp$data_source)
# #> atlantic_amphibians                             atlantic_ants                             atlantic_bats
# #>               15788                                    178976                                      9984
# #>      atlantic_birds                      atlantic_butterflies              atlantic_camera_trap_mammals
# #>               33391                                      7062                                     43068
# #>    atlantic_camtrap                         atlantic_epiphyte atlantic_flower_invertebrate_interactions
# #>                1820                                    121458                                     27225
# #>  atlantic_frugivory                          atlantic_mammals                atlantic_nonvolant_mammals
# #>               10374                                      4657                                      1046
# #> atlantic_pollination                         atlantic_primates                     atlantic_small_mammal
# #>                7524                                      2061                                      2620
# #>             dryflor
# #>               57180

## -----------------------------------------------------------------------------
# dp_araucaria <- get_datapaper(datapaper = c("atlantic", "dryflor"),
#                               species = "Araucaria angustifolia")
# #> Downloading data from atlantic datapapers...
# #> Downloading data from DryFlor...
# #> Datapaper(s) successfully retrieved.
# #>
# #> ##########################################################################
# #>   PLEASE, USE THE FUNCTION cite_datapaper() TO CITE DATAPAPERS RETRIEVED
# #> ##########################################################################
# 
# # Check the number of records retrieved per dataset
# table(dp_araucaria$data_source)
# #> atlantic_epiphyte           dryflor
# #>              518                 1

## -----------------------------------------------------------------------------
# cite_datapaper(data = dp_araucaria)
# #> ===============================================================================
# #>   PLEASE CITE THE FOLLOWING DATA PAPERS IN YOUR WORK:
# #> ===============================================================================
# #>
# #> [1] Data Source: 'dryflor'
# #> Dryflor, et al. (2016). Plant diversity patterns in neotropical dry forests and their conservation implications. Science, 353(6306), #> 1383-1387. https://doi.org/10.1126/science.aaf5080
# #>
# #> [2] Data Source: 'atlantic_epiphyte'
# #> Ramos, F. N., Mortara, S. R., Monalisa-Francisco, N., Elias, J. P. C., Neto, L. M., Freitas, L., Kersten, R., Amorim, A. M., Matos, F. B., #> Nunes-Freitas, A. F., Alcantara, S., Alexandre, M. H. N., De Almeida-Scabbia, R. J., De Almeida, O. J. G., Alves, F. E., De Oliveira Alves, #> R. M., Alvim, F. S., De Andrade, A. C. S., De Andrade, S., ... Ribeiro, M. C. (2019). ATLANTIC EPIPHYTES: A data set of vascular and #> non-vascular epiphyte plants and lichens from the Atlantic Forest. Ecology, 100(2), e02541. https://doi.org/10.1002/ecy.2541
# #>
# #> -------------------------------------------------------------------------------
# #> ATLANTIC Series Overview:
# #> Data Papers from a biodiversity hotspot: https://esajournals.onlinelibrary.wiley.com/doi/toc/10.1002/(ISSN)1939-9170.AtlanticPapers
# #> -------------------------------------------------------------------------------

## -----------------------------------------------------------------------------
# all_occ <- bind_here(occ_gbif, occ_sl, occ_bien, occ_idig, dp_araucaria)
# #> Error: All datasets must have the same columns.

## -----------------------------------------------------------------------------
# # Standardizing GBIF
# gbif_std <- format_columns(occ_gbif, metadata = "gbif")
# 
# # Standardizing SpeciesLink (checking for encoding issues)
# sl_std <- format_columns(occ_sl, metadata = "specieslink", check_encoding = TRUE)
# #> Warning: NAs introduced by coercion>
# 
# # Standardizing BIEN
# bien_std <- format_columns(occ_bien, metadata = "bien")
# 
# # Standardizing iDigBio
# idig_std <- format_columns(occ_idig, metadata = "idigbio")

## -----------------------------------------------------------------------------
# all_occ <- bind_here(gbif_std, sl_std, bien_std, idig_std, dp_araucaria)
# # Number of records by database
# table(all_occ$data_source)
# #>       bien        gbif     idigbio specieslink  atlantic_epiphyte    dryflor
# #>        137        3000        1271        1224               518           1

## ----eval = TRUE--------------------------------------------------------------
# Import data example
data("puma_atlanticr", package = "RuHere")

# Create metadata to standardize the occurrences
puma_metadata <- create_metadata(occ = puma_atlanticr,
                                 scientificName = "actual_species_name",
                                 decimalLongitude = "longitude",
                                 decimalLatitude = "latitude",
                                 elevation = "altitude",
                                 country = "country",
                                 stateProvince = "state",
                                 municipality = "municipality",
                                 locality = "study_location",
                                 year = "year_finish",
                                 habitat = "vegetation_type",
                                 datasetName = "reference")

# Now, we can use this metadata to standardize the columns
puma_occ <- format_columns(occ = puma_atlanticr, metadata = puma_metadata,
                           binomial_from = "actual_species_name",
                           data_source = "atlanticr")

head(puma_occ[, 1:5])

## -----------------------------------------------------------------------------
# occ_araucaria_cougar <- bind_here(all_occ, #Occurrences of Araucaria
#                                   puma_occ) #Occurrences of cougar
# # Number of records per species
# table(occ_araucaria_cougar$species)
# #> Araucaria angustifolia          Puma concolor
# #>                  6151                    139

## -----------------------------------------------------------------------------
# # Convert to spatial object
# occ_spatial <- spatialize(occ = occ_araucaria_cougar)
# 
# # Load mapview
# library(mapview)
# 
# # Plot the distribution using mapview
# mapview(occ_spatial, zcol = "species", layer.name = "Species", cex = 4)

## ----IMG01, eval=T, echo=F, fig.align='center', out.width='80%'---------------
knitr::include_graphics("vignettes_img/IMG01.jpeg")

