R语言 从嵌套列表动态构建路径

mqxuamgl  于 2023-04-09  发布在  其他
关注(0)|答案(1)|浏览(106)

具有此嵌套列表:

myList<-list()
myList[[length(myList)+1]]<-list(text="Grandfather01",tabName='tabnameGrandfather01')
myList[[length(myList)+1]]<-list(text="Grandfather02",
                                 list(text="Father02_01"
                                      ,list(text='Child02_01_01',tabName='tabNameChild02_01_01')
                                      ,list(text='Child02_01_02',tabName='tabNameChild02_01_02')
                                 )
                                )
myList[[length(myList)+1]]<-list(text="Grandfather03",
                                 list(text='Father03_01',tabName='tabNameFather03_01')
                              )

myList[[length(myList)+1]]<-list(text="Grandfather04"
                                 ,list(text="Father04_01"
                                       ,list(text='Child04_01_01'
                                             ,list(text='SuperChild04_01_01_01',tabName='tabNameSuperChild04_01_01_01')
                                             ,list(text='SuperChild04_01_01_02',tabName='tabNameSuperChild04_01_01_02')
                                       )      
                                 )
                                 ,list(text='Father05_01',tabName='tabNameFather05_01')
                              )

我需要建立一个路径列表,如:
第一元素包含:

/tabnameGrandfather01

第二个元素包含:

Grandfather02/Father02_01/tabNameChild02_01_01
Grandfather02/Father02_01/tabNameChild02_01_02

第三个元素包含:

Grandfather03/tabNameFather03_01

最后一个包含:

Grandfather04/Father04_01/Child04_01_01/tabNameSuperChild04_01_01_01
Grandfather04/Father04_01/Child04_01_01/tabNameSuperChild04_01_01_02
Grandfather04/tabNameFather05_01

有没有使用递归函数的想法?

kwvwclae

kwvwclae1#

你可以试试这个递归函数:

collapse <- function(x, root = NULL) {
    path <-
        if (length(x) == 2L && identical(names(x), c("text", "tabName")))
            x[[2L]]
        else unlist(lapply(x[-1L], sys.function(), x[[1L]]), FALSE, FALSE)
    if (is.null(root)) path else file.path(root, path)
}

lapply(myList, collapse)
[[1]]
[1] "tabnameGrandfather01"

[[2]]
[1] "Grandfather02/Father02_01/tabNameChild02_01_01"
[2] "Grandfather02/Father02_01/tabNameChild02_01_02"

[[3]]
[1] "Grandfather03/tabNameFather03_01"

[[4]]
[1] "Grandfather04/Father04_01/Child04_01_01/tabNameSuperChild04_01_01_01"
[2] "Grandfather04/Father04_01/Child04_01_01/tabNameSuperChild04_01_01_02"
[3] "Grandfather04/tabNameFather05_01"

相关问题