You need to enable JavaScript to run this app. R语言中统计同一分组内目标与其他变量水平共现的分组数
优惠活动
大模型
产品
解决方案
定价
更多

R语言中统计同一分组内目标与其他变量水平共现的分组数

共现航次统计实现方案

核心逻辑:先锁定所有出现目标物种(示例中为red)的航次集合,再统计这些航次内其余每个物种的出现频次,未共同出现的物种计数补0,即可匹配预期的结果格式。


方案1:基础R实现(无需额外安装包)

步骤拆解:

  • 筛选所有包含目标物种的航次ID
  • 提取这些航次对应的全部捕获记录
  • 对非目标物种按去重航次做频次统计
  • 对齐全量非目标物种列表,无共现记录的位置补0

可直接运行的代码:

# 设置目标物种
target_sp <- "red"

# 1. 提取存在目标物种的航次ID
target_trips <- unique(dat$trip[dat$color == target_sp])

# 2. 筛选这些航次的全部捕获记录
trip_record <- dat[dat$trip %in% target_trips, ]

# 3. 统计每个非目标物种的去重航次数
count_res <- aggregate(
  trip ~ color,
  data = trip_record[trip_record$color != target_sp, ],
  FUN = function(x) length(unique(x))
)
colnames(count_res) <- c("color2", "trips.with.red")

# 4. 对齐全量非目标物种列表,缺失值补0
all_other_sp <- setdiff(unique(dat$color), target_sp)
dat2 <- merge(
  data.frame(color2 = all_other_sp),
  count_res,
  by = "color2",
  all.x = TRUE
)
dat2$trips.with.red[is.na(dat2$trips.with.red)] <- 0

运行后输出结果与预期完全一致:

> dat2
   color2 trips.with.red
1   blue              0
2  green              1
3 orange              2
4 purple              0

如果需要和示例中的物种顺序完全匹配,可在最后追加一行排序代码:
dat2 <- dat2[match(c("orange","green","blue","purple"), dat2$color2), ]


方案2:dplyr/tidyverse 实现(高可读性,适配大数据集)

适合日常使用tidyverse生态做分析的场景,代码流程链路清晰:

library(dplyr)

target_sp <- "red"

dat2 <- dat %>%
  # 筛选所有包含目标物种的航次
  group_by(trip) %>%
  filter(target_sp %in% color) %>%
  ungroup() %>%
  # 排除目标物种本身的记录
  filter(color != target_sp) %>%
  # 去重后统计每个物种的航次数
  distinct(trip, color) %>%
  count(color, name = "trips.with.red") %>%
  # 对齐全量非目标物种,缺失值补0
  right_join(
    data.frame(color2 = setdiff(unique(dat$color), target_sp)),
    by = c("color" = "color2")
  ) %>%
  mutate(trips.with.red = replace_na(trips.with.red, 0)) %>%
  select(color2, trips.with.red)

方案3:高频次快速实现(适配超大规模数据集)

针对大样本量的渔业调查数据,用table函数的运算效率远高于逐行聚合,适合十万行以上的数据集场景:

target_sp <- "red"

# 提取存在目标物种的航次
target_trips <- unique(dat$trip[dat$color == target_sp])
# 统计这些航次中其他物种的出现频次
other_sp_freq <- table(dat$color[dat$trip %in% target_trips & dat$color != target_sp])
# 对齐物种列表生成结果,缺失值补0
all_other_sp <- setdiff(unique(dat$color), target_sp)
dat2 <- data.frame(
  color2 = all_other_sp,
  trips.with.red = as.integer(other_sp_freq[all_other_sp])
)
dat2$trips.with.red[is.na(dat2$trips.with.red)] <- 0

内容的提问来源于stack exchange,提问作者Dr.FishGirl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.22 15:24:05