Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 删除具有特定名称的列表元素_R_Nested Lists - Fatal编程技术网

R 删除具有特定名称的列表元素

R 删除具有特定名称的列表元素,r,nested-lists,R,Nested Lists,我有一个嵌套列表,需要删除所有具有特定名称的节点/元素。例如,在下面定义的R list()中,我想删除所有名为“lol”的节点。我注意到它可以出现在层次结构的不同层次上 扫描树并删除这些节点的最佳方法是什么 tree <- list( A = list( A_1 = list( A_1_1 = list(), A_1_2 = list() ), lol = "haha" ), B = list(

我有一个嵌套列表,需要删除所有具有特定名称的节点/元素。例如,在下面定义的R list()中,我想删除所有名为“lol”的节点。我注意到它可以出现在层次结构的不同层次上

扫描树并删除这些节点的最佳方法是什么

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

您可以创建一个简单的递归函数来删除这些元素:

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

foo谢谢,应该现在修复。看起来你更新了帖子。你们有其他嵌套的模式吗,比如说深嵌套的模式?谢谢。递归函数从来都不是我的强项。
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()