Get Elements from Nested Data Structure (2/2): Variants of pluck() - Check Nesting Depth, Element Presence, and Error Report

In this tutorial, we’ll discuss variant functions of pluck(). These functions are based on the same working principles as pluck(), but with a different output:


We’ll use the example below to demonstrate our functions.

library(purrr)
address1 <- list(street = "123 Main St", city = "Anytown", country = "USA")
person1 <- list(name = "John", age = 30, address = address1)
person2 <- list(name = "Alice", hobbies = c("painting", "biking"))
# Update json_data to include the new personpeople <- list("p1" = person1, "p2" = person2)

pluck_depth() calculates the level of nesting you can index into.

pluck_depth(address1)

Output:

[1] 2
pluck_depth(person1)

Output:

[1] 3
pluck_depth(people)

Output:

[1] 4

pluck_exists() checks if the specified element is present or not.

people %>%   pluck_exists("p1", "hobbies")

Output:

[1] FALSE
people %>%   pluck_exists("p2", "hobbies")

Output:

[1] TRUE

chuck() is just like pluck(), except that if the element you are trying to access does not exist (or is NULL), it will return an error. Compare the following between pluck() and chuck().

pluck(people, "p1", "hobbies")

Output:

NULL
chuck(people, "p1", "hobbies")# Error in `chuck()`:# ! Can't find name `hobbies` in vector.
pluck(people, 3)

Output:

NULL
chuck(people, 3)# Error in `chuck()`:# ! Index 1 exceeds the length of plucked object (3 > 2).

In comparison, [[ ]] returns NULL or error message for non-existing elements in a less consistent manner.

people[["p1"]][["hobbies"]]

Output:

NULL
people[[3]]# Error in people[[3]] : subscript out of bounds