R/IFNknn.R

Defines functions IFNknn

Documented in IFNknn

#' k-nearest neighbours for IFN plots
#'
#' Builds a weighted neighbouring object containing the k-nearest neighbours as well as the distances to them,
#' from a matrix of longitude/latitude coordinates.
#'
#' @param coords Matrix of plot coordinates in longitude and latitude, with plot IDs as row names.
#' @param k Number of neighbours to determine.
#' @param verbose Boolean flag to turn on console output informing of the calculation process.
#'
#' @return An object of class \code{list} with elements 'neighbours' and 'distances'. Plot IDs are stored in attribute 'IDs'
#' @export
#'
#' @examples
#'
#' # Load example plot coordinates
#' data(examplePlotCoords)
#' examplePlotCoords
#'
#' # Build neighbour object (only one neighbour)
#' nb = IFNknn(examplePlotCoords, k = 1)
#' nb
IFNknn<-function(coords, k = 57, verbose = TRUE) {
  # K-nearest neighbours
  if(verbose) cat(paste0("(a) Determining ",k,"-nearest neighbours - "))
  kn <- knearneigh(coords, k = k)

  #Transform to nb object
  if(verbose) cat(paste0("(b) Building 'nb' object - "))
  nb<-knn2nb(kn, row.names = rownames(coords))

  #Estimates distances from
  if(verbose) cat(paste0("(c) Calculating distances - "))
  nbd <- nbdists(nb, coords, longlat = TRUE)

  ids <- attr(nb, "region.id")
  attributes(nb)<-NULL
  attributes(nbd)<-NULL
  nb_w = list(neighbours = nb, distances = nbd)
  attr(nb_w, "ID") = ids

  if(verbose) cat(paste0("done."))
  return(nb_w)
}
miquelcaceres/IFNdyn documentation built on Feb. 1, 2021, 10:55 a.m.