R/SPtoSPDF.R

Defines functions SPtoSPDF

Documented in SPtoSPDF

#' @title Spatial* to Spatial*DataFrame
#'
#' @description
#' \code{SPtoSPDF} attaches a basic dataframe of numbered indexes to a
#' Spatial* object.
#'
#' @details
#' Insert details here.
#'
#' @param SP Spatial* object.
#'
#' @return Spatial*DataFrame object.
#' @export
# @examples need to find test data and add examples
SPtoSPDF <- function(SP) {
  if (!grepl("Spatial", class(SP))) {
    stop("Input into SPtoSPDF is not a \"Spatial*\" object")
  } else if (grepl("DataFrame", class(SP))) {
    stop("Input into SPtoSPDF is already a \"Spatial*DataFrame\" object")
  }

  if (grepl("Polygon", class(SP))) {
    pid <- sapply(slot(SP, "polygons"), function(x) slot(x, "ID"))
    p.df <- data.frame(ID=1:length(SP), row.names = pid)
    S_DF <- sp::SpatialPolygonsDataFrame(SP, p.df)
  } else if (grepl("Line", class(SP))) {
    lid <- sapply(slot(SP, "lines"), function(x) slot(x, "ID"))
    l.df <- data.frame(ID=1:length(SP), row.names = lid)
    S_DF <- sp::SpatialLinesDataFrame(SP, l.df)
  } else if (grepl("Point", class(SP))) {
    pid <- dimnames(slot(SP, "coords"))[[1]]
    p.df <- data.frame(ID=1:length(SP), row.names = pid)
    S_DF <- sp::SpatialPointsDataFrame(SP, p.df)
  }
  return(S_DF)
}
jacpete/jpfxns documentation built on May 16, 2020, 5:02 a.m.