Skip to content

Instantly share code, notes, and snippets.

@simbamangu
Created July 8, 2021 16:39
Show Gist options
  • Save simbamangu/78e4e31729feed4d138cfea4772bc1fc to your computer and use it in GitHub Desktop.
Save simbamangu/78e4e31729feed4d138cfea4772bc1fc to your computer and use it in GitHub Desktop.
# Download and analyse precipitation data for a polygon
# Libraries
library(raster)
library(sf)
library(rgdal)
library(utils) # For download.file
setwd("~/Downloads")
# Download and unarchive the file
download.file(url = "https://data.chc.ucsb.edu/products/CHIRPS-2.0/africa_monthly/bils/v2p0chirps202105.tar.gz",
destfile = "v2p0chirps202105.tar.gz", method = "auto")
untar("v2p0chirps202105.tar.gz")
# Load the raster and set NA values
r <- raster("v2p0chirps202105.bil", crs = "+proj=longlat +datum=WGS84")
values(r)[values(r) == -9999] <- NA # NA values
# Load the shapefile and convert to WGS84 lat/lon
p <- read_sf("Uluguru/Uluguru_disso.shp")
p <- st_transform(p, crs = 4326)
# Extract the values
p.mean <- extract(r, st_zm(p), fun = mean)
p.min <- extract(r, st_zm(p), fun = min)
p.max <- extract(r, st_zm(p), fun = max)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment