I have a list in R:
my_list <- list(a = 1, b = 2, c = list(d = 4, e = 5))
Suppose I don't know the structure of the list, but I know that somewhere in this list, there is an element named d
, nested or not. I would like to:
c
)Is there an easy method / package that can solve this seemingly simple problem?
To subset lists we can utilize the single bracket [ ] , double brackets [[ ]] , and dollar sign $ operators. Each approach provides a specific purpose and can be combined in different ways to achieve the following subsetting objectives: Subset list and preserve output as a list. Subset list and simplify output.
Lists in R can be subsetted using all three of the operators mentioned above, and all three are used for different purposes. The [[ operator can be used to extract single elements from a list. Here we extract the first element of the list.
We can use the [[index]] function to select an element in a list. The value inside the double square bracket represents the position of the item in a list we want to extract.
To extract only first element from a list, we can use sapply function and access the first element with double square brackets. For example, if we have a list called LIST that contains 5 elements each containing 20 elements then the first sub-element can be extracted by using the command sapply(LIST,"[[",1).
I'm implementing the suggestion by @r2evans. I'm sure this can be improved:
getParentChild <- function(lst, myN) {
myFun <- function(lst, myN) {
test <- which(names(lst) == myN)
if (length(test) > 0)
return(lst[test])
lapply(lst, function(x) {
if (is.list(x))
myFun(x, myN)
})
}
temp <- myFun(lst, myN)
temp[!sapply(temp, function(x) is.null(unlist(x)))]
}
getParentChild(my_list, "d")
$c
$c$d
[1] 4
Here is a more complicate example that illustrates how getParentChild
shows lineage when there are multiple children/grandchildren.
exotic_list <- list(a = 1, b = 2, c = list(d = 4, e = 5), f = list(g = 6, h = list(k = 7, j = 8)), l = list(m = 6, n = list(o = 7, p = 8)), q = list(r = 5, s = 11), t = 12)
getParentChild(exotic_list, "n")
$l
$l$n
$l$n$o
[1] 7
$l$n$p
[1] 8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With