基于双次捕捞耗尽法计算同一表格多物种种群数量估算
用R实现双次捕捞耗尽法计算渔业种群数量估算值
针对你提供的汇总捕捞数据,这里提供两种高效的R代码实现方案,自动计算符合条件物种的种群数量估算值(仅保留同时有两次捕捞数据的物种)。
方法1:使用tidyverse工具链(推荐,代码更直观)
首先加载tidyverse包,通过数据格式转换和分组计算实现需求:
library(tidyverse) # 示例数据集 dataex <- data.frame(Species= c("BRK","RGN","RGN","RBT","RBT"), PassCaptured = c(1,1,2,1,2), NumberCaptured = c(6,18,5,10,3)) # 计算种群估算值 pop_estimates <- dataex %>% # 将长格式数据转为宽格式,每个物种对应两次捕捞的捕获数 pivot_wider(names_from = PassCaptured, values_from = NumberCaptured, names_prefix = "Pass") %>% # 筛选同时存在两次捕捞数据的物种(排除仅单次捕捞的物种) filter(!is.na(Pass1), !is.na(Pass2)) %>% # 应用双次捕捞耗尽法公式计算N mutate(Popest = (Pass1^2)/(Pass1 - Pass2)) %>% # 保留目标列 select(Species, Popest) # 输出结果 print(pop_estimates)
代码说明:
pivot_wider:将原始长格式数据转换为宽格式,每个物种一行,Pass1和Pass2列分别存储两次捕捞的捕获数量;filter:剔除缺少第二次捕捞数据的物种(如示例中的BRK),确保仅计算有完整数据的物种;mutate:代入公式N = C1²/(C1-C2)计算种群估算值;select:仅保留物种名称和估算值两列,得到目标输出格式。
方法2:使用Base R(无需额外包)
如果不想加载第三方包,可以用Base R的分组处理功能实现:
# 示例数据集 dataex <- data.frame(Species= c("BRK","RGN","RGN","RBT","RBT"), PassCaptured = c(1,1,2,1,2), NumberCaptured = c(6,18,5,10,3)) # 按物种分组计算 species_results <- by(dataex, dataex$Species, function(group_data) { # 检查当前物种是否有两次捕捞数据 if (all(c(1, 2) %in% group_data$PassCaptured)) { C1 <- group_data$NumberCaptured[group_data$PassCaptured == 1] C2 <- group_data$NumberCaptured[group_data$PassCaptured == 2] pop_est <- (C1^2)/(C1 - C2) return(data.frame(Species = unique(group_data$Species), Popest = pop_est)) } }) # 合并有效结果并去除空值 pop_estimates_base <- do.call(rbind, Filter(Negate(is.null), species_results)) # 输出结果 print(pop_estimates_base)
代码说明:
by:按物种对数据分组,对每个分组执行自定义计算;- 分组内先验证是否存在两次捕捞数据,再提取
C1和C2代入公式计算; do.call(rbind, ...):将分组计算的结果合并为一个数据框,Filter剔除无有效数据的分组结果。
结果说明
运行代码后会得到符合要求的结果:
- RGN的估算值为
18²/(18-5) ≈ 24.92(你提供的示例期望输出中RGN的18应为笔误); - RBT的估算值为
10²/(10-3) ≈ 14.29(你提供的示例期望输出中RBT的35应为笔误,正确计算结果约为14.29)。
内容的提问来源于stack exchange,提问作者Rnchriz
相关产品推荐
相关产品推荐

