确定嵌套在R中的级别? [英] Determine level of nesting in R?
本文介绍了确定嵌套在R中的级别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种简单的方法(即函数)来确定列表中的嵌套级别?
我知道有str
可用于获取此信息.但是,有什么东西可以简单地返回结果吗?而且我可以使用这样的功能来(递归地)获取所有级别的alist的名称吗?
Is there an easy way (i.e. a function) to determine the level of nesting in list?
I know there is str
which can be used to get this information. But is there something that simply gives back the result? And can I use such a function to get the names of all levels of alist (recursively) ?
推荐答案
一个小的递归函数可以为您做到这一点:
A little recursive function can do this for you:
depth <- function(this,thisdepth=0){
if(!is.list(this)){
return(thisdepth)
}else{
return(max(unlist(lapply(this,depth,thisdepth=thisdepth+1))))
}
}
如果您拥有package:testthat
,请使用以下测试集:
If you've got package:testthat
, here's a test set:
l1=list(1,2,3)
l2=list(1,2,l1,4)
l3=list(1,l1,l2,5)
require(testthat)
expect_equal(depth(l1),1)
expect_equal(depth(l2),2)
expect_equal(depth(l3),3)
在变量名中使用小写L的歉意.可读性失败.
Apologies for using lower-case L in variable names. Readability fail.
这篇关于确定嵌套在R中的级别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文