library(raster)
## Loading required package: sp
r <- raster(volcano)
l <- as.image.SpatialGridDataFrame(as(r, "SpatialGridDataFrame"))
levs <- pretty(range(l$z, na.rm = TRUE))
Update for maptools::ContourLines2SLDF to ensure value is included as well as the unique factor level from contourLines.
cl2SLDF <- function (cL, proj4string = CRS(as.character(NA)))
{
if (length(cL) < 1L)
stop("cL too short")
lev_instances <- unlist(lapply(cL, "[[", "level"))
lev_group <- factor(lev_instances)
df <- data.frame(level = levels(lev_group),
value = unique(lev_instances), ## reasonably confident that contourLines returns these in sort order
stringsAsFactors = TRUE)
clcoords <- lapply(cL, function(x) cbind(x[["x"]], x[["y"]]))
m <- nlevels(lev_group)
res <- vector(mode = "list", length = m)
IDs <- paste("C", 1:m, sep = "_")
row.names(df) <- IDs
for (ilev in seq_len(nlevels(lev_group))) {
idx <- which(lev_group == levels(lev_group)[ilev])
res[[ilev]] <- Lines(lapply(clcoords[idx], Line), IDs[ilev])
}
SL <- SpatialLines(res, proj4string = proj4string)
res <- SpatialLinesDataFrame(SL, data = df)
res
}
cL <- contourLines(l, sort(sample(levs)))
plot(sf::st_as_sf(cl2SLDF(cL)))
text(.1, .2, lab = "1")
cL <- contourLines(l, sample(levs))
plot(sf::st_as_sf(cl2SLDF(cL)))
text(.1, .2, lab = "2")
cL <- contourLines(l, sample(levs))
plot(sf::st_as_sf(cl2SLDF(cL)))
text(.1, .2, lab = "3")
cL <- contourLines(l, sample(levs))
plot(sf::st_as_sf(cl2SLDF(cL)))
text(.1, .2, lab = "4")