library(rgbif)      # Descarga de datos GBIF
## Warning: package 'rgbif' was built under R version 4.4.3
library(dismo)      # Modelos de distribución, MaxEnt
## Warning: package 'dismo' was built under R version 4.4.3
## Loading required package: raster
## Loading required package: sp
## Warning: package 'sp' was built under R version 4.4.3
library(raster)     # Datos espaciales raster
library(sp)         # Objetos espaciales
library(sf)         # Datos espaciales modernos
## Warning: package 'sf' was built under R version 4.4.3
## Linking to GEOS 3.13.0, GDAL 3.10.1, PROJ 9.5.1; sf_use_s2() is TRUE
library(tidyverse)  # Limpieza de datos
## Warning: package 'ggplot2' was built under R version 4.4.3
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   4.0.0     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.1
## ✔ purrr     1.0.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ tidyr::extract() masks raster::extract()
## ✖ dplyr::filter()  masks stats::filter()
## ✖ dplyr::lag()     masks stats::lag()
## ✖ dplyr::select()  masks raster::select()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(ENMeval)    # Evaluación de modelos MaxEnt
## Warning: package 'ENMeval' was built under R version 4.4.3
## This is ENMeval version 2.0.5.2. 
## For worked examples, please consult the vignette: <https://jamiemkass.github.io/ENMeval/articles/ENMeval-2.0-vignette.html>.
library(maxnet)     # Implementación moderna de MaxEnt
## Warning: package 'maxnet' was built under R version 4.4.3
foc_data <- occ_search(
  scientificName = "Fusarium oxysporum f.sp. cubense",
  hasCoordinate = TRUE,
  limit = 2000
)

occ_df <- foc_data$data %>%
  filter(!is.na(decimalLatitude), !is.na(decimalLongitude)) %>%
  select(decimalLongitude, decimalLatitude, country, year)

# Convertir a puntos espaciales
occ_points <- st_as_sf(occ_df, coords = c("decimalLongitude", "decimalLatitude"), crs = 4326)
options(repos = c(CRAN = "https://cloud.r-project.org"))
install.packages("geodata")
## Installing package into 'C:/Users/luisc/AppData/Local/R/win-library/4.4'
## (as 'lib' is unspecified)
## package 'geodata' successfully unpacked and MD5 sums checked
## 
## The downloaded binary packages are in
##  C:\Users\luisc\AppData\Local\Temp\Rtmporevhg\downloaded_packages
library(geodata)
## Warning: package 'geodata' was built under R version 4.4.3
## Loading required package: terra
## Warning: package 'terra' was built under R version 4.4.3
## terra 1.8.70
## 
## Attaching package: 'terra'
## The following object is masked from 'package:tidyr':
## 
##     extract
library(raster)
# Descargar bioclimas de WorldClim v2.1
bio <- worldclim_global(var = "bio", res = 10, path = "data")

# Cargar en un objeto tipo stack
bio_stack <- stack(bio)
# Descargar solo Sudamérica y a menor resolución
bio <- worldclim_country("COL", var = "bio", res = 10, path = "data")
bio_stack <- stack(bio)
extent_region <- extent(-180, 180, -40, 40)
bio_crop <- crop(bio_stack, extent_region)

plot(bio_crop[[1]], main = "Temperatura Media Anual (Bio1)")

# --- DESCARGA Y LIMPIEZA DE DATOS GBIF ---
library(rgbif)
library(dplyr)
library(CoordinateCleaner)
## Warning: package 'CoordinateCleaner' was built under R version 4.4.3
library(sf)

# Descargar datos de Fusarium oxysporum f. sp. cubense
foc_data <- occ_search(
  scientificName = "Fusarium oxysporum f.sp. cubense",
  hasCoordinate = TRUE,
  limit = 2000
)

# Extraer coordenadas y columnas relevantes
occ_df <- foc_data$data %>%
  select(decimalLongitude, decimalLatitude, country, year) %>%
  filter(!is.na(decimalLongitude), !is.na(decimalLatitude))

# Agregar columna species (requerida por CoordinateCleaner)
occ_df$species <- "Fusarium oxysporum f.sp. cubense"

# Limpiar coordenadas
occ_clean <- clean_coordinates(
  x = occ_df,
  lon = "decimalLongitude",
  lat = "decimalLatitude",
  species = "species",    # 👈 agregar este argumento
  tests = c("centroids", "equal", "gbif", "institutions", "zeros")
)
## Testing coordinate validity
## Flagged 0 records.
## Testing equal lat/lon
## Flagged 0 records.
## Testing zero coordinates
## Flagged 0 records.
## Testing country centroids
## Flagged 0 records.
## Testing GBIF headquarters, flagging records around Copenhagen
## Flagged 0 records.
## Testing biodiversity institutions
## Flagged 1 records.
## Flagged 1 of 2000 records, EQ = 0.
# Filtrar solo los registros válidos
occ_final <- occ_clean %>%
  filter(.summary == TRUE)

# Verificar cuántos puntos válidos hay
nrow(occ_final)
## [1] 1999
# --- Instalar/cargar paquetes ---
if (!requireNamespace("geodata", quietly = TRUE)) install.packages("geodata")
if (!requireNamespace("terra",   quietly = TRUE)) install.packages("terra")
if (!requireNamespace("raster",  quietly = TRUE)) install.packages("raster")

library(geodata)
library(terra)
library(raster)

# --- Opciones útiles (si tu red requiere otro método de descarga) ---
# options(download.file.method = "libcurl")

# --- Descargar WorldClim v2.1 (Bio1-Bio19) a 10' (elige res = 10, 5, 2.5 según memoria) ---
# path = "data" crea la carpeta data en tu working directory y guarda los archivos allí
bio_spat <- worldclim_global(var = "bio", res = 10, path = "data")

# Comprobar clase del objeto descargado
print(class(bio_spat))
## [1] "SpatRaster"
## attr(,"package")
## [1] "terra"
# --- Recortar a tu región de interés (ejemplo: América del Sur) ---
# Ajusta los límites (xmin, xmax, ymin, ymax) a lo que necesites
myext <- ext(-90, -30, -60, 15)   # ejemplo: Sudamérica

if (inherits(bio_spat, "SpatRaster")) {
  # trabajar con terra
  bio_crop_spat <- terra::crop(bio_spat, myext)
  # Si necesitas compatibilidad con dismo (objeto raster), convertir:
  bio_crop <- raster::stack(bio_crop_spat)
} else {
  # Si se devolvió otro tipo (por seguridad)
  bio_stack <- try(stack(bio_spat), silent = TRUE)
  if (inherits(bio_stack, "try-error")) stop("No se pudo convertir worldclim a RasterStack.")
  bio_crop <- crop(bio_stack, extent(myext))
}

# --- Verificación rápida y muestra de la capa Bio1 ---
print(bio_crop)
## class      : RasterStack 
## dimensions : 450, 360, 162000, 19  (nrow, ncol, ncell, nlayers)
## resolution : 0.1666667, 0.1666667  (x, y)
## extent     : -90, -30, -60, 15  (xmin, xmax, ymin, ymax)
## crs        : +proj=longlat +datum=WGS84 +no_defs 
## names      : wc2.1_10m_bio_1, wc2.1_10m_bio_2, wc2.1_10m_bio_3, wc2.1_10m_bio_4, wc2.1_10m_bio_5, wc2.1_10m_bio_6, wc2.1_10m_bio_7, wc2.1_10m_bio_8, wc2.1_10m_bio_9, wc2.1_10m_bio_10, wc2.1_10m_bio_11, wc2.1_10m_bio_12, wc2.1_10m_bio_13, wc2.1_10m_bio_14, wc2.1_10m_bio_15, ... 
## min values :       -8.238740,        2.056667,       24.484125,        9.648387,        1.222362,      -17.617750,        5.900000,      -11.999458,       -6.036708,        -3.496208,       -13.127167,         0.000000,         0.000000,         0.000000,         0.000000, ... 
## max values :        29.39055,        19.02594,        94.78897,       678.34088,        36.59700,        24.70000,        34.98175,        29.51181,        29.46729,         30.74362,         28.16318,       7150.00000,        908.00000,        484.00000,        203.72603, ...
plot(bio_crop[[1]], main = "Bio1 — Temperatura media anual")
# Añadir puntos de presencia (usa occ_final que ya creaste)
points(occ_final$decimalLongitude, occ_final$decimalLatitude, pch = 19, cex = 0.6, col = "red")

# --- CREAR PUNTOS DE BACKGROUND (PSEUDO-AUSENCIAS) ---
# bio_crop: stack de variables bioclimáticas
# n: número de puntos de fondo (puedes ajustar según el tamaño del área)
set.seed(123)
bg <- randomPoints(bio_crop, n = 10000)

# Visualización rápida para verificar
plot(bio_crop[[1]], main = "Puntos de presencia y fondo")
points(occ_final$decimalLongitude, occ_final$decimalLatitude, pch = 19, col = "red", cex = 0.7)
points(bg, pch = 19, col = "blue", cex = 0.3)

# --- AJUSTE DEL MODELO MAXENT ---
pres_coords <- occ_final[, c("decimalLongitude", "decimalLatitude")]
mx_model <- maxent(x = bio_crop, p = pres_coords, a = bg)
## Warning in .local(x, p, ...): 1 (16.67%) of the presence points have NA
## predictor values
## Loading required namespace: rJava
# --- EVALUAR EL MODELO ---
response(mx_model)

plot(mx_model)

library(dismo)

# Preparar coordenadas
pres_coords <- occ_final[, c("decimalLongitude", "decimalLatitude")]

# Entrenar modelo
foc_model <- maxent(
  x = bio_crop,
  p = pres_coords,
  a = bg
)
## Warning in .local(x, p, ...): 1 (16.67%) of the presence points have NA
## predictor values

R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

summary(cars)
##      speed           dist       
##  Min.   : 4.0   Min.   :  2.00  
##  1st Qu.:12.0   1st Qu.: 26.00  
##  Median :15.0   Median : 36.00  
##  Mean   :15.4   Mean   : 42.98  
##  3rd Qu.:19.0   3rd Qu.: 56.00  
##  Max.   :25.0   Max.   :120.00

Including Plots

You can also embed plots, for example:

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.