source("zscripts/z_inputFls.R")
source("zscripts/z_helpFX.R") # and the Help function just in case :-)
7 Megafauna and Ocean Fronts
7.1 Data import
Source the required dataset.
Or you can actually do the step-by-step.
###################################
####### Whale Shark (mmf dataset)
###################################
# Read the files
<- readRDS("data/mm_mmf/MMF_WhaleSharkTracks_Madagascar.rds")
ws01 <- readRDS("data/mm_mmf/MMF_WhaleSharkTracks_Mozambique.rds")
ws02 # Merge
<- rbind(ws01, ws02) %>%
wsF ::mutate(group = "Whale Shark")
dplyr# Monthly split
<- wsF %>%
wsF01 ::filter(dates %in% wsF$dates[stringr::str_detect(string = wsF$dates, pattern = "2016-10.*")])
dplyr<- wsF %>%
wsF02 ::filter(dates %in% wsF$dates[stringr::str_detect(string = wsF$dates, pattern = "2016-11.*")])
dplyr<- wsF %>%
wsF03 ::filter(dates %in% wsF$dates[stringr::str_detect(string = wsF$dates, pattern = "2016-12.*")])
dplyr
<- wsF %>%
wsF04 ::filter(dates %in% wsF$dates[stringr::str_detect(string = wsF$dates, pattern = "2011-07.*")])
dplyr<- wsF %>%
wsF05 ::filter(dates %in% wsF$dates[stringr::str_detect(string = wsF$dates, pattern = "2011-08.*")])
dplyr<- wsF %>%
wsF06 ::filter(dates %in% wsF$dates[stringr::str_detect(string = wsF$dates, pattern = "2011-09.*")])
dplyr<- wsF %>%
wsF07 ::filter(dates %in% wsF$dates[stringr::str_detect(string = wsF$dates, pattern = "2011-10.*")])
dplyr<- wsF %>%
wsF08 ::filter(dates %in% wsF$dates[stringr::str_detect(string = wsF$dates, pattern = "2011-11.*")])
dplyr<- wsF %>%
wsF09 ::filter(dates %in% wsF$dates[stringr::str_detect(string = wsF$dates, pattern = "2011-12.*")]) dplyr
7.2 Plotting and testing
# Getting the "help" scripts from source
source("zscripts/z_inputFls.R")
terra 1.7.39
Linking to GEOS 3.11.0, GDAL 3.5.3, PROJ 9.1.0; sf_use_s2() is TRUE
Attaching package: 'dplyr'
The following objects are masked from 'package:terra':
intersect, union
The following objects are masked from 'package:stats':
filter, lag
The following objects are masked from 'package:base':
intersect, setdiff, setequal, union
Attaching package: 'tidyr'
The following object is masked from 'package:terra':
extract
source("zscripts/z_helpFX.R") # and the Help function just in case :-)
Attaching package: 'patchwork'
The following object is masked from 'package:terra':
area
The legacy packages maptools, rgdal, and rgeos, underpinning the sp package,
which was just loaded, will retire in October 2023.
Please refer to R-spatial evolution reports for details, especially
https://r-spatial.org/r/2023/05/15/evolution4.html.
It may be desirable to make the sf package available;
package maintainers should consider adding sf to Suggests:.
The sp package is now running under evolution status 2
(status 2 uses the sf package in place of rgdal)
Support for Spatial objects (`sp`) will be deprecated in {rnaturalearth} and will be removed in a future release of the package. Please use `sf` objects with {rnaturalearth}. For example: `ne_download(returnclass = 'sf')`
Attaching package: 'rnaturalearthdata'
The following object is masked from 'package:rnaturalearth':
countries110
Attaching package: 'gganimate'
The following object is masked from 'package:terra':
animate
Attaching package: 'transformr'
The following object is masked from 'package:sf':
st_normalize
Attaching package: 'data.table'
The following objects are masked from 'package:dplyr':
between, first, last
The following object is masked from 'package:terra':
shift
udunits database from /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/library/units/share/udunits/udunits2.xml
Linking to liblwgeom 3.0.0beta1 r16016, GEOS 3.11.0, PROJ 9.1.0
Loading required package: foreach
Loading required package: gifski
Loading required package: ggnewscale
Loading required package: pals
Warning: attribute variables are assumed to be spatially constant throughout
all geometries
# Pick a random object from above
<- wsF01 %>%
mmF_test st_transform(crs = robin) # always remember to get a common projection!
# Plot
<- ggplot() +
p_test geom_sf(data = mmF_test, colour = "blue", size = 0.3) +
geom_sf(data = world_sfRob, size = 0.05, fill = "grey20")
print(p_test)
7.3 Near distance to Fronts
source("zscripts/z_inputFls.R")
source("zscripts/z_helpFX.R")
# loading libraries
library(sf)
library(terra)
library(stringr)
library(dplyr)
library(data.table)
library(ggplot2)
library(patchwork)
# defining the arguments
= "data/PUs_MZ_100km2.shp"
pus = "data/fsle_pus_100km2/FSLE_SWIO_2011-12.rds"
fsle_sf = wsF09
fdata = 0.75
cutoff = "data/"
output
# Read the front dataset
<- st_read(pus)
PUs <- readRDS(fsle_sf)
sf1 <- names(sf1) %>%
nms ::str_extract(pattern = ".*(?=\\.)")
stringrcolnames(sf1) <- nms
# Matching the appropriate Front data set with the megafauna component
# (from fronts data [sf1] pick the same DATES of megafauna data [fdata])
<- sf1 %>%
df01 ::select(as.character(unique(fdata$dates)))
dplyr
# A loop to match data with front and extract which is the closest value
<- unique(fdata$dates)
Fdates <- vector("list", length = length(Fdates))
FF for(i in seq_along(Fdates)) {
# Filter the megafauna data for each date
<- fdata %>%
mmF ::filter(dates == Fdates[i]) %>%
dplyrst_transform(crs = robin)
# Filter Front data for each date of the megafauna data
<- df01 %>%
OFCdates ::select(as.character(Fdates[i]))
dplyr<- cbind(PUs, OFCdates) %>%
OFCdates st_transform(crs = robin)
# Estimate the distance to all
<- st_distance(mmF, OFCdates, by_element = FALSE) %>%
dist02 t() %>%
as_tibble()
colnames(dist02) <- as.character(mmF$ptt)
# Get the upper front quantile
<- OFCdates %>%
qfront as_tibble() %>%
::select(2) %>%
dplyr# as.vector() %>%
quantile(probs = cutoff, na.rm = TRUE) %>%
as.vector()
# First 5 FIRST closest distances to a nearest Front
<- apply(X = dist02, MARGIN = 2, FUN = function(x) {
dist03 <- x
dist <- cbind(PUs[,1], OFCdates[,2], dist) %>%
final as_tibble() %>%
::select(-geometry, -geometry.1) %>%
dplyr::filter(.[[2]] > qfront) %>%
dplyr::arrange(.[[3]]) %>%
dplyr::slice(1:5)
dplyr
})<- do.call(cbind, dist03)
FF[[i]]
}
# Tidy up the final list
names(FF) <- Fdates
<- FF[order(names(FF))]
FF
# File name for the output
<- unlist(stringr::str_split(basename(pus), "_"))[3] %>%
ngrd ::str_remove_all(pattern = ".shp")
stringr<- unlist(stringr::str_split(basename(fsle_sf), "_"))[3] %>%
ndate ::str_remove_all(pattern = ".rds")
stringr<- paste("cutoff", cutoff, sep = "-")
th <- paste("whale-shark_neardist", ngrd, ndate, th, sep = "_")
ffname saveRDS(FF, paste0(output, ffname, ".rds"))
7.4 Clean (yes, even more!)
<- readRDS("data/whale-shark_neardist_100km2_2011-12_cutoff-0.75.rds")
dt <- lapply(dt, function(x) {
exm <- x
sngl <- split.default(sngl, rep(1:(ncol(sngl)/3), each = 3))
df1 <- units::set_units(unlist(lapply(df1, function(x2) x2[1,3])), "m")
dist1 <- as.vector(dist1)})
dist2 <- paste0(unlist(stringr::str_split(names(exm)[1], pattern = "-"))[1:2], collapse = "-")
Fdates #
<- Reduce(c, exm) %>%
dst1 ::set_units("m") %>%
units::set_units("km")
units<- dst1 %>%
lsout as_tibble() %>%
::mutate(date = as.factor(Fdates)) %>%
dplyr::rename(neardist = value) %>%
dplyr::select(date, neardist) dplyr
7.5 Distance Histograms
# Getting the dates
<- lsout
s1 <- as.vector(unique(s1$date))
Fdates
# Plotting
<- ggplot(data = s1, aes(x = neardist, fill = date)) +
ff geom_histogram(data = subset(s1, date == Fdates),
aes(x = neardist, y = (..count..)/sum(..count..)),
colour = "1",
bins = 30) +
scale_fill_manual(values = c("#2b8cbe"),
name = "",
labels = Fdates) +
scale_y_continuous(breaks = seq(0, 1, 0.2), limits = c(0, 1)) +
coord_cartesian(xlim = c(0, 30)) +
theme_bw() +
theme(plot.title = element_text(face = "plain", size = 20, hjust = 0.5),
plot.tag = element_text(colour = "black", face = "bold", size = 23),
axis.title.y = element_blank(),
axis.title.x = element_text(size = rel(1.5), angle = 0),
axis.text.x = element_text(size = rel(2), angle = 0),
axis.text.y = element_text(size = rel(2), angle = 0),
legend.title = element_text(colour = "black", face = "bold", size = 15),
legend.text = element_text(colour = "black", face = "bold", size = 13),
legend.key.height = unit(1.5, "cm"),
legend.key.width = unit(1.5, "cm"),
legend.position = "none") +
labs(x = "Distance to high FSLE",
y = "Density") +
# geom_richtext(inherit.aes = FALSE,
# data = tibble(x = 27, y = 0.8, label = paste("n", "=", nrow(s1), sep = " ")),
# aes(x = x, y = y, label = "label"),
# size = 6,
# fill = NA) +
ggtitle(Fdates)