确定R中的嵌套级别? [英] Determine level of nesting in R?

查看:18
本文介绍了确定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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆