dcl
dcl

Reputation: 939

Removing list elements that have a specific name

I've got a nested list and I need to remove all the nodes/elements that have a specific name. For example, in the following defined R list(), I'd like to remove all nodes that have the name 'lol'. I note that it can appear at different levels of the hierarchy.

What's the best way to scan through the tree and remove those nodes?

tree <- list(
    A = list(
        A_1 = list(
            A_1_1 = list(), A_1_2 = list()
        ),
        lol = "haha"
    ),
    B = list(
        B_1 = list(
            B_1_1 = list(), B_1_2 = list(), lol = "rofl"
        )
    )
)

I'd like to perform some action on the tree object so that result becomes:

$A
$A$A_1
$A$A_1$A_1_1
list()

$A$A_1$A_1_2
list()



$B
$B$B_1
$B$B_1$B_1_1
list()

$B$B_1$B_1_2
list()

Upvotes: 4

Views: 582

Answers (1)

talat
talat

Reputation: 70256

You can create a simple recursive function function to remove those elements:

foo <- function(x) {
  x <- x[names(x) != "lol"]
  if(is.list(x)) lapply(x, foo)
}

foo(tree)
# $A
# $A$A_1
# $A$A_1$A_1_1
# list()
# 
# $A$A_1$A_1_2
# list()
# 
# 
# 
# $B
# $B$B_1
# $B$B_1$B_1_1
# list()
# 
# $B$B_1$B_1_2
# list()

Upvotes: 4

Related Questions