sf (version 0.2-8)

st_cast: Cast geometry to another type: either simplify, or cast explicitly

Description

Cast geometry to another type: either simplify, or cast explicitly

Usage

"st_cast"(x, to, ...)
"st_cast"(x, to, ...)
"st_cast"(x, to, ...)
"st_cast"(x, to, ...)
"st_cast"(x, to, ...)
"st_cast"(x, to, ...)
"st_cast"(x, to, ...)
st_cast(x, to, ...)
"st_cast"(x, to, ..., ids = seq_along(x))
"st_cast"(x, to, ..., ids = seq_len(nrow(x)), FUN, warn = TRUE)

Arguments

x
object of class sfg, sfc or sf
to
character; target type, if missing, simplification is tried; when x is of type sfg (i.e., a single geometry) then to needs to be specified.
...
ignored
ids
integer vector, denoting how geometries should be grouped (default: no grouping)
FUN
function passed on to aggregate, in case ids was specified and attributes need to be grouped
warn
logical; if TRUE, warn if attributes are assigned to sub-geometries

Value

object of class to if successful, or unmodified object if unsuccesful. If information gets lost while type casting, a warning is raised.

Examples

Run this code
example(st_read)
mpl <- nc$geometry[[4]]
#st_cast(x) ## error 'argument "to" is missing, with no default'
cast_all <- function(xg) {
  lapply(c("MULTIPOLYGON", "MULTILINESTRING", "MULTIPOINT", "POLYGON", "LINESTRING", "POINT"), 
      function(x) st_cast(xg, x))
}
st_sfc(cast_all(mpl))
## no closing coordinates should remain for multipoint
any(duplicated(unclass(st_cast(mpl, "MULTIPOINT"))))  ## should be FALSE
## number of duplicated coordinates in the linestrings should equal the number of polygon rings 
## (... in this case, won't always be true)
sum(duplicated(do.call(rbind, unclass(st_cast(mpl, "MULTILINESTRING"))))
     ) == sum(unlist(lapply(mpl, length)))  ## should be TRUE

p1 <- structure(c(0, 1, 3, 2, 1, 0, 0, 0, 2, 4, 4, 0), .Dim = c(6L, 2L))
p2 <- structure(c(1, 1, 2, 1, 1, 2, 2, 1), .Dim = c(4L, 2L))
st_polygon(list(p1, p2))
mls <- st_cast(nc$geometry[[4]], "MULTILINESTRING")
st_sfc(cast_all(mls))
mpt <- st_cast(nc$geometry[[4]], "MULTIPOINT")
st_sfc(cast_all(mpt))
pl <- st_cast(nc$geometry[[4]], "POLYGON")
st_sfc(cast_all(pl))
ls <- st_cast(nc$geometry[[4]], "LINESTRING")
st_sfc(cast_all(ls))
pt <- st_cast(nc$geometry[[4]], "POINT")
## st_sfc(cast_all(pt))  ## Error: cannot create MULTIPOLYGON from POINT 
st_sfc(lapply(c("POINT", "MULTIPOINT"), function(x) st_cast(pt, x)))
s = st_multipoint(rbind(c(1,0)))
st_cast(s, "POINT")

Run the code above in your browser using DataLab