Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subset a list without knowing its structure in r

Tags:

r

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:

  1. Subset that list element, without knowing the structure of the master list that contains it
  2. Know the name of its parent list (i.e. element c)

Is there an easy method / package that can solve this seemingly simple problem?

like image 257
Jacob Nelson Avatar asked Mar 15 '18 17:03

Jacob Nelson


People also ask

How do I subset data from a list in R?

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.

Can you subset a list in R?

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.

How do I select an element from a list in R?

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.

How do I extract the first element of a list in R?

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


1 Answers

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
like image 57
Joseph Wood Avatar answered Sep 28 '22 06:09

Joseph Wood