UpsideDownRide
UpsideDownRide

Reputation: 558

How to iterate easily over leafs of a nested list

Let's say I have a following list:

a <- list(a = 1, b = list(a = list(b = 1, c = 2), c = 1), c = 1)

and I would like to delete all the leafs with the name c. How do I do this in an idiomatic way? It seems like a job suited for rapply but using rapply I cannot figure out a way to access the name of the list element I'm currently iterating over.

Upvotes: 0

Views: 43

Answers (2)

talat
talat

Reputation: 70326

You can do this with a recursive lapply-function, for example:

foo <- function(x, name) {
  if(any(idx <- names(x) == name)) x <- x[!idx]
  if(is.list(x)) lapply(x, foo, name) else x
}

foo(a, "c")
# $a
# [1] 1
# 
# $b
# $b$a
# $b$a$b
# [1] 1

Upvotes: 1

karen
karen

Reputation: 812

What about this?

a <- list(a = 1, b = list(a = list(b = 1, c = 2), c = 1), c = 1)

aunls <- unlist(a)
aunls[!grepl('c', names(aunls))]

and after you can just nest again doing or lapply using the names structure.

Upvotes: 1

Related Questions