# NOT RUN {
# pluck() supports integer positions, string names, and functions.
# Using functions, you can easily extend pluck(). Let's create a
# list of data structures:
obj1 <- list("a", list(1, elt = "foobar"))
obj2 <- list("b", list(2, elt = "foobaz"))
x <- list(obj1, obj2)
# And now an accessor for these complex data structures:
my_element <- function(x) x[[2]]$elt
# The accessor can then be passed to pluck:
pluck(x, 1, my_element)
pluck(x, 2, my_element)
# Even for this simple data structure, this is more readable than
# the alternative form because it requires you to read both from
# right-to-left and from left-to-right in different parts of the
# expression:
my_element(x[[1]])
# This technique is used for plucking into attributes with
# attr_getter(). It takes an attribute name and returns a function
# to access the attribute:
obj1 <- structure("obj", obj_attr = "foo")
obj2 <- structure("obj", obj_attr = "bar")
x <- list(obj1, obj2)
# pluck() is handy for extracting deeply into a data structure.
# Here we'll first extract by position, then by attribute:
pluck(x, 1, attr_getter("obj_attr")) # From first object
pluck(x, 2, attr_getter("obj_attr")) # From second object
# pluck() splices lists of arguments automatically. The following
# pluck is equivalent to the one above:
idx <- list(1, attr_getter("obj_attr"))
pluck(x, idx)
# }
Run the code above in your browser using DataLab