gpt4 book ai didi

r - 嵌套列表中的唯一类

转载 作者:行者123 更新时间:2023-12-04 11:35:03 25 4
gpt4 key购买 nike

我正在寻找一种直接的方法来获取嵌套列表中第一级元素的唯一类。

可重现的例子:

x = list(list(1,"A"), # Unique classes:  character, numeric
4, # Unique classes: numeric
list(1,2,list(4,5, list(6)))) # Unique classes: numeric

# Expected return: list(c('character', 'numeric'), c('numeric'), c('numeric'))

最佳答案

这有效

list_classes <- function(ls) {
unique(sapply(ls, class))
}

lapply(x, list_classes)

#[[1]]
#[1] "numeric" "character"

#[[2]]
#[1] "numeric"

#[[3]]
#[1] "numeric" "list"

编辑:递归版本
list_classes <- function(ls) {

# get classes of list
cls <- sapply(ls, class)

# which are lists themselves
which_ls <- cls == "list"
lists <- ls[which_ls]

# which are non lists
non_lists <- cls[!which_ls]

# recursively evaluate contents of list for their classes
return(
unique(
c(non_lists, sapply(lists, list_classes), recursive = T)
)
)

}

lapply(x, list_classes)


#[[1]]
#[1] "numeric" "character"

#[[2]]
#[1] "numeric"

#[[3]]
#[1] "numeric"

关于r - 嵌套列表中的唯一类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40084542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com