按名称删除嵌套R列表中的元素

时间:2016-06-16 08:21:44

标签: r list

我有一个像这样的嵌套元素

> x <- list(a=list(from="me", id="xyz"), b=list(comment=list(list(message="blabla", id="abc"), list(message="humbug", id="jkl"))), id="123")
> str(x)
List of 3
 $ a :List of 2
  ..$ from: chr "me"
  ..$ id  : chr "xyz"
 $ b :List of 1
  ..$ comment:List of 2
  .. ..$ :List of 2
  .. .. ..$ message: chr "blabla"
  .. .. ..$ id     : chr "abc"
  .. ..$ :List of 2
  .. .. ..$ message: chr "humbug"
  .. .. ..$ id     : chr "jkl"
 $ id: chr "123"

如何在列表的所有级别中删除名称为id的所有元素?即预期的输出是

> str(x)
List of 2
 $ a:List of 1
  ..$ from: chr "me"
 $ b:List of 1
  ..$ comment:List of 2
  .. ..$ :List of 1
  .. .. ..$ message: chr "blabla"
  .. ..$ :List of 1
  .. .. ..$ message: chr "humbug"

使用rlist软件包的解决方案特别受欢迎,但我对任何有效的方法感到满意。

2 个答案:

答案 0 :(得分:6)

递归也是我如何做到的:

# recursive function to remove name from all levels of list
stripname <- function(x, name) {
    thisdepth <- depth(x)
    if (thisdepth == 0) {
        return(x)
    } else if (length(nameIndex <- which(names(x) == name))) {
        x <- x[-nameIndex]
    }
    return(lapply(x, stripname, name))
}

# function to find depth of a list element
# see http://stackoverflow.com/questions/13432863/determine-level-of-nesting-in-r
depth <- function(this, thisdepth=0){
    if (!is.list(this)) {
        return(thisdepth)
    } else{
        return(max(unlist(lapply(this,depth,thisdepth=thisdepth+1))))    
    }
}


str(stripname(x, "id"))
## List of 2
## $ a:List of 1
## ..$ from: chr "me"
## $ b:List of 1
## ..$ comment:List of 2
## .. ..$ :List of 1
## .. ..$ :List of 1
## .. .. ..$ message: chr "blabla"
## .. .. ..$ message: chr "humbug"

答案 1 :(得分:2)

的静脉中尝试递归函数
f <- function(i) 
  lapply(i, function(x) 
    if (is.list(x)) { 
      if(!is.null(names(x))) f(x[names(x)!="id"]) else f(x) 
    } else x
  )
str(f(x[names(x)!="id"]))
# List of 2
#  $ a:List of 1
#   ..$ from: chr "me"
#  $ b:List of 1
#   ..$ comment:List of 2
#   .. ..$ :List of 1
#   .. .. ..$ message: chr "blabla"
#   .. ..$ :List of 1
#   .. .. ..$ message: chr "humbug"