R/distcalc.R

#' Calculate exact distances in meters between plots for performing distance decay analyses
#'
#' @ indf = matrix containing community data
#' @ plotno = character vector indicating column name for altitude values
#' @ group =character vector indicating column name for elevational gradient IDs (if there is more than one stuy area)
#'

distcalc<-function(indf,island,plotno){
    results<-NULL
    # unique list of islands
    isl.l<-as.character(unique(indf@data[,island]))
    # loop through islands
    for (i in 1:length(isl.l)){
        # subset island
        tmp<-indf[indf@data[,island] %in% isl.l[i],]
        # unique plot number so to get rid plots in excess from index
        plotno.l<-sort(unique(tmp@data[,plotno]))
        # get rid of non-existing plots from decayinfo
        plotno.l.df<-decayinfo[decayinfo$NBX %in% plotno.l,]
        plotno.l.df<-plotno.l.df[plotno.l.df$NBY %in% plotno.l,]
        # loop through sites
        for (j in 1:dim(plotno.l.df)[1]){
            # row j and column 1 vs. row j and column 2
            plotjcol1<-tmp[tmp@data[,plotno] %in% plotno.l.df[j,1],]
            plotjcol2<-tmp[tmp@data[,plotno] %in% plotno.l.df[j,2],]
            distancedf<-data.frame(Island=isl.l[i],NBX=plotno.l.df[j,1],
            NBY=plotno.l.df[j,2],dist=spDistsN1(pts=plotjcol1,pt=plotjcol2))
            results<-rbind(distancedf,results)
        }
        # merge with correct island coding info
    }
    lookupdf<-data.frame(Islandnew=c("GOM","MAD2","Pico","TEN","TER","MAD1"),
      Island=c("Gomera","Madeira Island 2","Pico","Tenerife","Terceira","Madeira Island 1"))
    suppressMessages(left_join(results,lookupdf)) %>%
      dplyr::select(Islandnew,NBX,NBY,dist) %>%
      rename(Island = Islandnew) -> decayinfo1
    return(decayinfo1)
}
drmarcogir/Rmacdiv documentation built on May 15, 2019, 12:58 p.m.