# Install the libraries if you don't have them
install.packages("spatstat")
install.packages("dplyr")

# THen load the libraries
library("dplyr")
library("spatstat")

# Use the environment tab to IMPORT the .csv file melan_df.csv

#  Have a look to see if it loaded

glimpse(melan_df)

# Check sample sizes
melan_df %>%
  dplyr::group_by(uni.fish) %>%
  dplyr::summarise(n = n())

# We make a new variable to label each treatment uniquely, called uni.fish
melan_df$uni.fish <- paste(melan_df$Embryo,melan_df$Treatment)
unique(melan_df$uni.fish)

# ======================== START OF DISTANCE ++++++++++++++++
# This is the Start of the LOOPs to extract all the nearest neighbour points

# START RUN FROM HERE AS ONE CHUNK OF CODE UNTIL 

# graphical parameter
par(oma = c(2,0.2,0.2,0.2))
for (i in 1:length(unique(melan_df$uni.fish))){
  
  melan_df.sub <- melan_df %>%
    dplyr::filter(uni.fish == unique(melan_df$uni.fish)[i])
  
  w <- ripras(melan_df.sub$x,melan_df.sub$y, shape = "convex")
  melan_df.sub.ppp <- ppp(melan_df.sub$x,melan_df.sub$y,  window = w)
  par(mfrow=c(1,3))
  plot(melan_df.sub.ppp, main = paste(unique(melan_df.sub$uni.fish),":", length(melan_df.sub$uni.fish), "cells"))
  
# Calculating and plotting Ripley's K, second order test 
  
  # THE dotted red line in the center symbolises complete spatial randomness (with the shaded area showing confidence limits).
  # If the black line is within the shaded area = random pattern
  # IF above- distances are closer than expected = aggregated
  # If BELOW - distances are greater than expected === PATTERN! !!! THIS IS THE IMPORTANT ONE
  K <- Kest(melan_df.sub.ppp, main = unique(melan_df.sub$uni.fish) ,correction = "translate")
  plot(envelope(melan_df.sub.ppp, Kest,nsim = length(melan_df.sub$x), fix.n = T),legend = F, cbind(hi,lo) ~ r, main = unique(melan_df.sub$uni.fish))
  plot(K,main = paste(main = unique(melan_df.sub$uni.fish),"K function"), add = T, legend = T)
  
# Calculating and plotting Nearest Neighbour second order test   
  # SAME INTERPRETATION AS ABOVE, just a different method.
  G <- Gest(melan_df.sub.ppp, correction = "km")
  plot(envelope(melan_df.sub.ppp, Gest,nsim = length(melan_df.sub$x), fix.n = T),legend = F, cbind(hi,lo) ~ r, main = unique(melan_df.sub$uni.fish))
  plot(G,main = paste(main = unique(melan_df.sub$uni.fish),"K function"), add = T, legend = T)
}# END of LOOP

# ================    RUN THE CODE UNTIL HERE ================
### ======================= END OF LOOPS ====================
### ======================= END OF LOOPS ====================
### ======================= END OF LOOPS ====================
# Then use the window to the right to scroll through the different graphs.

