R/lcbdwrap.R

#' Function for calculating local contribution to beta diversity following the
#' methods of Legendre and Caceres (2013)
#'
#' @ 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 )
#'

lcbdwrap<-function(spdat,sp.grouping){

    # ---first step: spider dissimilarity matrices
    spdist<-vector("list")
    # list to loop through
    comp.l<-unique(spdat$comp)
    isl.l<-unique(spdat$site)
    hab.l<-as.character(unique(spdat[,sp.grouping]))
    for (i in 1:3){
        # subset by biodiversity component
        t1<-subset(decayres,comp==comp.l[i])
        for (j in 1:length(isl.l)){
            # subset by island
            t2<-subset(t1,site==isl.l[j])
            for (z in 1:length(hab.l)){
                # subset by species grouping (formerly habitat)
                t3<-t2[t2[,sp.grouping] %in% hab.l[z],]
                # new plot names
                t3$p1<-stri_split_fixed(t3$comparison,"-",simplify=T)[,1]
                t3$p2<-stri_split_fixed(t3$comparison,"-",simplify=T)[,2]
                # dissimilarity matrix
                betavals <-t3[,c("beta")]
                nams <- with(t3, unique(c(as.character(p1), as.character(p2))))
                attributes(betavals) <- with(t3, list(Size = length(nams),
                                                      Labels = nams,
                                                      Diag = FALSE,
                                                      Upper = FALSE,
                                                      method = "user"))
                class(betavals) <- "dist"
                betavals1<-list(betavals)
                names(betavals1)<-paste(comp.l[i],"_",isl.l[j],"_",gsub(" ",".",hab.l[z]),sep="")
                spdist<-append(spdist,betavals1)
            }
        }
    }
    # ---second step: compute LCBD metric
    # loop through distance matrices
    results<-NULL
    for (i in 1:length(spdist)){
        # calculate lcbd (non-euclidean)
        sitecont=LCBDcomp(D=spdist[[i]],sqrt.D = TRUE)
        # create labels
        mylabs<-stri_split_fixed(names(spdist[i]),"_",simplify=T)
        res<-data.frame(lcbd=sitecont$LCBD,MACDIVCode=1:length(sitecont$LCBD),
                        comp=mylabs[,1],Island=mylabs[,2],sp.group=mylabs[,3])
        results<-rbind(res,results)
    }
    return(results)
}
drmarcogir/Rmacdiv documentation built on May 15, 2019, 12:58 p.m.