如何在嵌套列表的叶子上轻松迭代

时间:2021-06-27 14:30:38

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.

我想删除所有名称为c的叶子。我该如何以惯用的方式做到这一点?这似乎是一个适合rapply的工作但是使用rapply我无法找到一种方法来访问我正在迭代的列表元素的名称。

2 个解决方案

#1


1  

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.

然后你可以再次使用名称结构进行嵌套或使用lapply。

#2


1  

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

您可以使用递归lapply函数执行此操作,例如:

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

#1


1  

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.

然后你可以再次使用名称结构进行嵌套或使用lapply。

#2


1  

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

您可以使用递归lapply函数执行此操作,例如:

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