嵌套列表中的唯一类

时间:2016-10-17 10:53:39

标签: r list nested

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

可重复的例子:

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'))

1 个答案:

答案 0 :(得分:6)

这有效

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"