有没有一种“内置的”/高效且稳健的方法来检查列表对象是否嵌套?
为了澄清我对术语“嵌套”的理解:
平面或非嵌套列表
x.1 <- list(
a=TRUE,
b=1:5
)
嵌套列表
x.2 <- list(
a=list(a.1=list(a.1.1=TRUE)),
b=list(b.1=1:5)
)
我的第一个想法是使用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
第二种方法由Roman和Arun提供:
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
any(sapply(x.2, function(x) class(x) == "list"))
。any(sapply(x.1, function(x) class(x) == "list"))
返回FALSE。 - Roman Luštrikany(sapply(my_list, class) == "list")
- Arunany(.)
已经提供了TRUE/FALSE
。你不必将其包装在`if语句(或分配为FALSE)中。 - Arun