R/buffertop1.R

Defines functions buffertop1

#' Create buffers and extract topographic information
#' Input is a raster and a matrix of with site coordinates
#' @inrast = input raster
#' @inpoint = column containing species names
#' @bufsize = buffer radius size
#' @rastcell= cell size of the raster
#'


buffertop1<-function(inrast,inpoint,bufsize){
    results<-NULL
    # loop through sites
    for (i in 1:dim(inpoint)[1]){
        cat(paste("... Processing site",i," ...",sep=" "))
        cat("\n")
        # create buffer
        for(j in 1:length(bufsize)){
            cat(paste("... Buffer size",bufsize[j]," ...",sep=" "))
            cat("\n")
            points <- SpatialPoints(inpoint[i,])
            pbuf <- gBuffer(points, width=bufsize[j])
            # loop through maps
            for (y in 1:length(inrast)){
                tmpr<-crop(inrast[[y]],pbuf)
                buf <- mask(tmpr, pbuf)
                # extract information from buffer
                bufdf<-rastertodf(buf)
                resdf<-data.frame(mean=mean(bufdf$value),variable=names(inrast)[y],size=bufsize[j],
                                  Island=inpoint[i,]@data$Islandnew,
                                  Database.code=inpoint[i,]@data$Database.code)
                results<-rbind(resdf,results)
            }
        }
    }
    # get results into a list
   size.l<-unique(results$size)
    results.l<-vector("list",length(size.l))
    names(results.l)<-size.l
    for (i in 1:length(size.l)){
        tmp<-subset(results,size==size.l[i])
        tmp %>%
            dplyr::select(-size) %>%
            gather(variable1,value,-c(Island,variable,Database.code)) %>%
            mutate(widename=paste(variable,variable1,sep="_")) %>%
            dplyr::select(Island,Database.code,value,widename)  %>%
            spread(widename,value) ->tmp1
        results.l[[i]]<-tmp1
    }
    return(results.l)
}
marcog77/Rmacdiv documentation built on May 9, 2018, 8:38 p.m.