#Adapt the working directory here
setwd("")

#GET THE DATA--------------

coord=read.csv("CPR_Data_Coordinates_NorthSea19582018.csv")
eye=read.csv("CPR_Data_DataEyecount_NorthSea19582018.csv")
trav=read.csv("CPR_Data_DataTraverse_NorthSea19582018.csv")
phyto=read.csv("CPR_Data_DataPhyto_NorthSea19582018.csv")

eyetaxa=read.csv("CPR_Data_ListEyecount.csv")
colnames(eye)=eyetaxa$taxon_name

travtaxa=read.csv("CPR_Data_ListTraverse.csv")
colnames(trav)=travtaxa$taxon_name

phytotaxa=read.csv("CPR_Data_ListPhyto.csv")
colnames(phyto)=phytotaxa$taxon_name


#grouping the data by standard area----------
abunzones=list()

for (i in unique(coord$List_StdareaName)){
  abunzones[[i]][["Coord"]]=coord[which(coord$List_StdareaName==i),]
  abunzones[[i]][["Eye"]]=eye[which(coord$List_StdareaName==i),]
  abunzones[[i]][["Trav"]]=trav[which(coord$List_StdareaName==i),]
  abunzones[[i]][["Phyto"]]=phyto[which(coord$List_StdareaName==i),]
}

#Get the monthly means----------------------

for (i in names(abunzones)){
  index=as.character(abunzones[[i]]$Coord$Year+(abunzones[[i]]$Coord$Month/12)-(1/24))
  
  abunzones[[i]][["EyeByMonths"]]=apply(abunzones[[i]]$Eye,2,tapply,index,mean,na.rm=T)
  abunzones[[i]][["TravByMonths"]]=apply(abunzones[[i]]$Trav,2,tapply,index,mean,na.rm=T)
  abunzones[[i]][["PhytoByMonths"]]=apply(abunzones[[i]]$Phyto,2,tapply,index,mean,na.rm=T)
  
  print(paste(i,"done!"))
}


save(abunzones,file="abunzones.RData")

