destructure: Destructure an object

Description Usage Arguments Details See Also Examples

View source: R/destructure.R

Description

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.

Usage

1

Arguments

x

An R object.

Details

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).

See Also

%<-%

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# 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'

zeallot documentation built on May 2, 2019, 3:17 p.m.