GarrettLab / HabitatConnectivity

geohabnet R package
https://garrettlab.github.io/HabitatConnectivity/
GNU General Public License v3.0
7 stars 4 forks source link

GBIF - global database for all organisms. So extract only the applicable ones and provide users to select from. It uses scientific names. #38

Open krishnakeshav opened 1 year ago

krishnakeshav commented 1 year ago

Sample -

Please try the code below where we can download information directly from GBIF and then convert that info into raster files of a desired resolution. In this case, myTaxon asks for the scientific name of the host (plant) instead of the common name: say, "Persea americana" instead of "avocado". Let me know if it works on your side. Also, the user needs to create an account in GBIF and then use his/her credentials. (For the moment, I trust that people in this repo can see my credentials). lol

library(rgbif)

# User provide a taxon name and R generates the taxon key to search in GBIF
# Or user provide the taxon key directly
myTaxon <- c("Persea americana")
taxonkey <- name_backbone(myTaxon)$usageKey

# Downloading info from GBIF
downloadID<-occ_download(
  pred_in("taxonKey", taxonkey),
  format = "SIMPLE_CSV",
  user = username, pwd = password, email = email
)

hostOccGBIF<-occ_download_get(downloadID[1]) %>%
  occ_download_import()

# Cleaning dataset
hostOccGBIF<-hostOccGBIF[hostOccGBIF$countryCode != "",]
hostOccGBIF<-hostOccGBIF[hostOccGBIF$countryCode != "ZZ",]
hostOccGBIF<-hostOccGBIF[hostOccGBIF$occurrenceStatus == "PRESENT",]
hostOccGBIF$Lon <- as.numeric(hostOccGBIF$decimalLongitude)
hostOccGBIF$Lat <- as.numeric(hostOccGBIF$decimalLatitude)
hostOccGBIF<-hostOccGBIF[,colnames(hostOccGBIF) %in% 
                           c("species", "Lon", "Lat")]
hostOccGBIF<-hostOccGBIF[is.na(hostOccGBIF$Lon)==FALSE, ]
hostOccGBIF<-hostOccGBIF[is.na(hostOccGBIF$Lat)==FALSE, ]
length(hostOccGBIF$species)

library(terra)
vectorHost<-vect(hostOccGBIF, crs="+proj=longlat", geom=c("Lon","Lat"))
e <- ext(-180, 180, -60, 90) #left, right, bottom, top
vectorHost<-crop(vectorHost, e)
r <- rast(res=0.5, ext=e) # res=1 here is equivalent to resolution=12 in geohabnet
rasterHost<-rasterize(vectorHost, r, fun=length)
plot(rasterHost)
# Optional: Applying the spatial operation named focal to mitigate sampling bias
frasterHost<-focal(rasterHost, 3, mean, na.policy="all", na.rm=TRUE)
plot(frasterHost)