检查列表是否嵌套

Rap*_*ter 3 nested r list nested-lists

是否有"内置"/高效且可靠的方法来检查列表对象是否嵌套?

澄清我对嵌套术语的理解:

扁平或非嵌套列表

x.1 <- list(
    a=TRUE, 
    b=1:5
)
Run Code Online (Sandbox Code Playgroud)

嵌套列表

x.2 <- list(
    a=list(a.1=list(a.1.1=TRUE)), 
    b=list(b.1=1:5)
)
Run Code Online (Sandbox Code Playgroud)

我的第一个想法是使用的组合str,capture.output和正则表达式.但是因为一切都与正则表达式相关:非常强大,在稳健性方面风险很大;-)所以我想知道是否有更好的东西:

isNested <- function(x) {
    if (class(x) != "list") {
        stop("Expecting 'x' to be a list")
    }
    out <- FALSE
    strout <- capture.output(str(x))
    idx <- grep("\\$.*List", strout)
    if (length(idx)) {
        out <- TRUE
    }
    return(out)
}

> isNested(x=x.1)
[1] FALSE
> isNested(x=x.2)
[1] TRUE
Run Code Online (Sandbox Code Playgroud)

第二种方法由罗曼和阿伦提供:

isNested2 <- function(x) {
    if (class(x) != "list") {
        stop("Expecting 'x' to be a list")
    }
    out <- any(sapply(x, is.list))
    return(out)
}

> isNested2(x=x.1)
[1] FALSE
> isNested2(x=x.2)
[1] TRUE
Run Code Online (Sandbox Code Playgroud)

Sve*_*ein 7

你可以使用这个is.list功能:

any(sapply(x.1, is.list))
[1] FALSE

any(sapply(x.2, is.list))
[1] TRUE
Run Code Online (Sandbox Code Playgroud)

作为一个功能isNested:

isNested <- function(l) {
  stopifnot(is.list(l))
  for (i in l) {
    if (is.list(i)) return(TRUE)
  }
  return(FALSE)
}
Run Code Online (Sandbox Code Playgroud)

该函数在检测到嵌套列表后立即停止,而不是测试所有列表元素.