library(ape)
library(plyr)
spatial<-read.csv("/Users/Ang/Documents/Tesis New/Spatial autocorrelation/Center coords for spatial analysis.csv")
species<-read.csv("/Users/Ang/Documents/Tesis New/Univariates/clean_all.csv")
sp<-na.omit(species)
#calculating mean abundances & richness per site
sp.site <- ddply(sp, .(Site), summarise, Meanabund = mean(Abund), Meanrich = mean(Morphosp.rich))
#combining 'sp.site' and 'spatial' dataframes
sp.space<-merge(sp.site,spatial,by="Site",all.x=TRUE)
###all=T tells R to include all rows from the 1st table, but not unmatched rows from the 2nd,
##to save that into a csv file
spspace<-write.csv(sp.space, file = "spspace.csv")
###Calculating Moran's I (source:http://www.ats.ucla.edu/stat/r/faq/morans_i.htm). For interpretation, see http://pro.arcgis.com/en/pro-app/tool-reference/spatial-statistics/h-how-spatial-autocorrelation-moran-s-i-spatial-st.htm
#Generate a distance matrix for sites close to each other:
site.dists <- as.matrix(dist(cbind(sp.space$Lon, sp.space$Lat)))
#then take inverse of the matrix values
site.dists.inv <- 1/site.dists
#and replace the diagonal entries with zero:
diag(site.dists.inv) <- 0
#view 1st 5 rows:
site.dists.inv[1:5, 1:5]
## 1 2 3 4 5
## 1 0.00000 11.16268 14.35688 11.20682 11.83148
## 2 11.16268 0.00000 45.34683 22.42611 154.04163
## 3 14.35688 45.34683 0.00000 27.83218 51.07678
## 4 11.20682 22.42611 27.83218 0.00000 21.07066
## 5 11.83148 154.04163 51.07678 21.07066 0.00000
Moran.I(sp.space$Meanabund, site.dists.inv)
## $observed
## [1] -0.01325189
##
## $expected
## [1] -0.05263158
##
## $sd
## [1] 0.06679702
##
## $p.value
## [1] 0.5554974
Moran.I(sp.space$Meanrich, site.dists.inv)
## $observed
## [1] -0.06172021
##
## $expected
## [1] -0.05263158
##
## $sd
## [1] 0.06828164
##
## $p.value
## [1] 0.8941103
Wooooohoo p>0.05, we can NOT reject the Ho that there is zero spatial autocorrelation => no spatial problem AT THE PATCH SCALE for either abundance (p=0.5) or for richness (p=0.8) :) Worth trying Mantel test and repeating analysis at treehole scale