You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建仅包含多深度存在物种的新DataFrame?

解决方案:筛选存在于多个深度的物种

针对你的需求,我们可以通过以下步骤在R中实现目标筛选:

1. 识别符合条件的物种

我们需要找出那些在至少两个不同深度中存在非零丰度的物种。可以按深度分组,统计每个物种在多少个深度出现过非零值:

# 先安装并加载dplyr包(未安装则运行 install.packages("dplyr"))
library(dplyr)

# 按depth分组,统计每个物种在不同深度的非零出现次数
species_depth_count <- df1 %>%
  group_by(depth) %>%
  summarise(across(starts_with("sp"), ~any(. > 0))) %>%
  summarise(across(starts_with("sp"), sum))

# 筛选出在≥2个深度出现的物种
selected_species <- names(species_depth_count)[species_depth_count >= 2]

2. 生成目标DataFrame

保留原数据的sample和depth列,加上筛选后的物种列:

df2 <- df1 %>%
  select(sample, depth, all_of(selected_species))

验证结果

运行后打印df2即可确认结果与你提供的示例一致:

print(df2)

输出:

sample depth sp2 sp4
1      a    10   1   1
2      b    20   4   0
3      c    30   6   5
4      d    10   5   4
5      e    20   3   3
6      f    30   1   7
7      g    10   5   8
8      h    20   6   4
9      i    30   4   1

内容的提问来源于stack exchange,提问作者mbroadribb

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 07:31:17