如何计算物种矩阵中每行的特有物种数量并生成统计列表?
计算物种矩阵中每行(样带)的特有物种数量
核心思路
特有物种的定义是:仅在某一行(样带)出现(丰度>0)、其他行均无记录的物种。要计算每行的特有物种数量,分两步:
- 识别所有特有物种:统计每个物种在多少行有非0记录,筛选出仅在1行出现的物种
- 对每行,统计这些特有物种中在该行有非0记录的数量
Base R 解决方案
直接用基础R函数实现,无需额外包:
# 示例数据 example_data <- data.frame(Species1 = c(1, 2, 3, 4, 5), Species2 = c(6, 7, 8, 9, 10), Species3 = c(0, 0, 13, 0, 0), Species4 = c(0, 0, 0, 0, 20), Species5 = c(0, 0, 23, 0, 0)) # 1. 计算每个物种的出现行数(有多少行丰度>0) species_occur_rows <- colSums(example_data > 0) # 2. 筛选出特有物种(仅在1行出现) endemic_species <- names(species_occur_rows)[species_occur_rows == 1] # 3. 计算每行的特有物种数量 row_endemic_counts <- rowSums(example_data[, endemic_species] > 0) # 查看结果 row_endemic_counts # 输出:0 0 2 0 1
Tidyverse 解决方案
如果习惯使用dplyr等tidyverse工具,可以用管道流实现:
library(dplyr) example_data <- data.frame(Species1 = c(1, 2, 3, 4, 5), Species2 = c(6, 7, 8, 9, 10), Species3 = c(0, 0, 13, 0, 0), Species4 = c(0, 0, 0, 0, 20), Species5 = c(0, 0, 23, 0, 0)) # 识别特有物种 endemic_species <- example_data %>% summarise(across(everything(), ~sum(.x > 0))) %>% t() %>% as.data.frame() %>% filter(V1 == 1) %>% rownames() # 计算每行的特有物种数量 row_endemic_counts <- example_data %>% mutate(endemic_count = rowSums(across(all_of(endemic_species), ~.x > 0))) %>% pull(endemic_count) # 查看结果 row_endemic_counts # 输出:0 0 2 0 1
关键说明
- 用
sum(.x > 0)统计物种出现行数,而非直接统计非0值总和,是因为只要物种仅在一行出现,无论丰度是1还是大于1,都属于特有物种 - 结果包含所有行的计数,无特有物种的行显示为0,完全匹配需求
内容的提问来源于stack exchange,提问作者Claire
相关产品推荐
相关产品推荐

