子集一个列表,然后在每个子列表上使用table()

时间:2019-03-11 16:12:32

标签: r

我有一个包含属性的1200种物种的列表,存储为矢量:

x <- list(Species1=c("A", "B", "C"), Species2=c("A","C","D"), Species3=c("B", "C","E"))

向量的长度不同。对于x中的每个物种,我都有生物分类信息:

tax <- data.frame(Species=c("Species1", "Species2", "Species3"), Taxa=c("Apes", "Birds", "Apes"))

我想

table(unlist(x))

但用x子集tax$Taxa

所需的输出

Apes

谢谢!

1 个答案:

答案 0 :(得分:2)

我们将名为stack的{​​{1}} list放入具有“ tax”数据集的两列“ data.frame” merge中,并获得table列的子集

table(merge(stack(x), tax, by.x = "ind", by.y = "Species")[3:2])
#     values
#Taxa    A B C D E
#  Apes  1 2 2 0 1
#  Birds 1 0 1 1 0

或使用tidyverse

library(tidvyerse)
set_names(x, tax$Taxa[match(names(x), tax$Species)]) %>%
   enframe %>% 
   unnest %>% 
   count(name, value) %>% 
   spread(value, n, fill = 0)