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

可重现的示例:

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/

10-12 22:24