Destructure an object
destructure is used during unpacking assignment to coerce an object
into a list. Individual elements of the list are assigned to names on the
left-hand side of the unpacking assignment expression.
destructure(x)
x |
An R object. |
If x is atomic destructure expects length(x) to be 1. If a vector with
length greater than 1 is passed to destructure an error is raised.
New implementations of destructure can be very simple. A new
destructure implementation might only strip away the class of a custom
object and return the underlying list structure. Alternatively, an object
might destructure into a nested set of values and may require a more
complicated implementation. In either case, new implementations must return a
list object so %<-% can handle the returned value(s).
# data frames become a list of columns
destructure(
data.frame(x = 0:4, y = 5:9)
)
# strings are split into list of characters
destructure("abcdef")
# dates become list of year, month, and day
destructure(Sys.Date())
# create a new destructure implementation
shape <- function(sides = 4, color = "red") {
structure(
list(sides = sides, color = color),
class = "shape"
)
}
## Not run:
# cannot destructure the shape object yet
c(sides, color) %<-% shape()
## End(Not run)
# implement `destructure` for shapes
destructure.shape <- function(x) {
list(x$sides, x$color)
}
# now we can destructure shape objects
c(sides, color) %<-% destructure(shape())
sides # 4
color # "red"
c(sides, color) %<-% destructure(shape(3, "green"))
sides # 3
color # 'green'Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.