library(purrr)
<- list(street = "123 Main St", address1 city = "Anytown", country = "USA")
<- list(name = "John", person1 age = 30, address = address1)
<- list(name = "Alice", person2 hobbies = c("painting", "biking"))
# Update json_data to include the new person<- list("p1" = person1, "p2" = person2) people
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:
pluck_depth()
calculates the level of nesting.pluck_exists()
checks if the specified element is present or not.chuck()
is likepluck()
but returns an error for non-existing elements to be extracted.
We’ll use the example below to demonstrate our functions.
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.
"p1"]][["hobbies"]] people[[
Output:
NULL
3]] people[[# Error in people[[3]] : subscript out of bounds