#' @title SpatialPoints* to SpatialLines*
#'
#' @description
#' \code{SPPointstoSPLine} creates SpatialLines or SpatialLinesDataFrame from
#' SpatialPoints or SpatialPointsDataFrame.
#'
#' @details
#' Required inputs are a SpatialPoints or SpatialPointsDataFrame, and a
#' data.frame with an "id" or "ID" field or id input parameter.
#' Some sort of id must be included. I hope a future version will remove this
#' requirement. I just don't have time now.
#'
#' @param sp SpatialPoints* object.
#' @param df datafame object for creating SpatialLinesDataFrame.
#' @param id ID vector for output line. Optional if dataframe has an 'ID' or
#' 'id' column
#' @param lineLength Logical. Should output dataframe include a column for
#' line length in meters
#'
#' @return SpatialLines* object.
#' @export
# @examples need to find test data and add examples
SPPointstoSPLines <- function(sp = NULL, df = NULL, id = NULL, lineLength = T) {
### SP is required
if (is.null(sp)) {
stop("Must Input Spatial Points Data")
}
### SP must be of class
if (class(sp) != "SpatialPoints") {
if (class(sp) != "SpatialPointsDataFrame") {
stop("\"sp\" Input not of class \'SpatialPoints\' or \'SpatialPointsDataFrame\'")
}
}
if (is.null(df)) {
output <- "SP"
if (is.null(id)) {
stop("Input is missing \"df\" and \"id\" field: Must have at least one")
} else if (!is.null(id)) {
if (length(id) != 1) {
stop("Input \"id\" must have a length of 1")
}
ID <- id
}
} else {
if (class(df) != "data.frame") {
stop("Input \"df\" is not of class \'data.frame\'")
}
output <- "SPDF"
if (!is.null(id)) {
if (length(id) != 1) {
stop("Input \"id\" must have a length of 1")
}
ID <- id
} else if (any(c("ID", "id") %in% colnames(df))) {
if ("ID" %in% colnames(df)) {
ID <- df$ID[1]
} else if ("id" %in% colnames(df)) {
ID <- df$id[1]
}
} else if (is.null(id)) {
stop("Input \"df\" does not have a column with name \'id\' or \'ID\' and Input \"id\" is NULL: Must have at least one")
}
}
if (is.factor(ID)) {
ID <- as.character(ID)
}
CooRS = sp@proj4string@projargs
if (is.null(CooRS) | is.na(CooRS)) {
stop("Issues with Coordinate System: sp@proj4string@projargs is NULL or NA")
}
pointcoord <- as.data.frame(coordinates(sp))
Slo1 <- Line(pointcoord)
Sli1<-Lines(list(Slo1),ID=ID)
LineSP <- SpatialLines(list(Sli1), proj4string=CRS(CooRS))
if (!is.null(df)) {
row.names(df) <- ID
}
if (!is.null(df) & lineLength == T) {
df$Length_m <- LineLength(Slo1, sum = T)
}
if (output == "SP") {
return(LineSP)
} else if (output == "SPDF") {
LineSPDF <- SpatialLinesDataFrame(LineSP, df, match.ID = F)
return(LineSPDF)
}
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.