Remove duplicates within the same raster cell

We downloaded layers at a spatial resolution of approximately 5x5 Km. This means that it is possible that within the same cell fall more than one occurrence. Despite the coordinates of two occurrences falling in the same cell can be different, technically they are just a duplicate of the environmental information provided by the raster. We want to remove this duplicate (analogously to what we did in Module 1) to remove the potential bias introduced by duplications. To do this we will use an ad.hoc function written for this purpose:

occ.desaggregation_RASTER<-function(df, colxy, colvar, rast, plot=T)
{
    require(raster)
    df_ini<-df
    var1<-cellFromXY(rast, df[,colxy])
    if(any(is.na(var1))){stop("no NA admitted in species occurrences!")}
    var2<-split(var1, var1)
    l<-sapply(var2, length)
    l1<-l[l>1]
    for(j in 1:length(l1))
    {
        w<-which(var1%in%as.numeric(names(l1[j])))
        found<-df[w,]
        s<-sample(w,1)
        df[w[w!=s],colxy]<-NA
    }
    df_final<-df[!is.na(df[,colxy[1]]),]
   if(plot==T)
   {
      x11()
       plot(df_ini[,colxy],main="distribution of occurences",sub=paste("# initial (black):",nrow(df_ini)," | # kept (red): ",nrow(df_final)),pch=19,col="black",cex=0.5)
       points(df_final[,colxy],pch=19,col="red",cex=0.2)
    }
       return(df_final)
}

Now we apply the new function  occ.desaggregation_RASTER to the krameri datasets:

> krameri<-occ.desaggregation_RASTER(df=krameri,colxy=c(2,1), rast=r[[1]], plot=F)


and check the new datafile:

>dim( krameri)

[1] 481

Do you remember the initial number of occurrences downloaded from GBIF? More than 8000. Now we have “only” 481 occurrences!