R/betabetween.R

#' Function for calculating beta diversity between plots following the
#' methods of Carvalho et al. (2012)
#'
#' @ indat = matrix containing community data
#' @ plotno = character vector indicating column name for altitude values
#' @ group =character vector indicating column name for site IDs (if there is more than one site )
#'
#'

betabetween<- function(indat=NULL,plotno=NULL,group=NULL,from=NULL) {
    indat<-as.data.frame(indat)
        results <- NULL
        site.l<-unique(indat[,group])
        for (i in 1:length(site.l)){
            indat1<-indat[indat[,group] %in% site.l[i],]
            indat.tmp<-indat[,from:dim(indat1)[2]]
            totalsp <- colSums(indat.tmp)
            cols <- names(totalsp[totalsp > 0])
            cols1 <- c(plotno,group,cols)
            indat2 <- indat1[, cols1]
            plotno.l<-sort(unique(indat2[,plotno]))
            for (y in 1:(length(plotno.l)- 1)){
                d1<-indat2[indat2[,plotno] %in% plotno.l[y],]
                d2<-indat2[indat2[,plotno] %in% plotno.l[y+ 1],]
                Btotal <- NULL
                Brepl <- NULL
                Brich <- NULL
                for (z in 1:dim(d1)[1]) {
                    d1<-d1[,!names(d1) %in% c(plotno,group)]
                    d2<-d2[,!names(d2) %in% c(plotno,group)]
                    commBoth <- as.matrix(rbind(d1,d2))
                    betaValues <- betaObs(comm = commBoth, func = "jaccard", abund = FALSE)
                    Btotal[z] <- betaValues$Btotal
                    Brepl[z] <- betaValues$Brepl
                    Brich[z] <- betaValues$Brich
                }
                res <- data.frame(site=site.l[i],Btotal = mean(Btotal), Brepl = mean(Brepl),Brich = mean(Brich), Plots=paste(plotno.l[y],plotno.l[y+1],sep="-"))
                results <- rbind(res, results)
            }
        }
       gather(results,key=fraction,value=beta,-c(Plots,site))  %>%
           filter(fraction!="Btotal") ->results1
       # change factor levels
       results1$Plots<-factor(paste("Plots ",results1$Plots,sep=""),levels=c("Plots 1-2","Plots 2-3","Plots 3-4","Plots 4-5","Plots 5-6"))
    return(results1)
}
drmarcogir/Rmacdiv documentation built on May 15, 2019, 12:58 p.m.