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

如何在R中按条件识别样地物种观测异同以生成韦恩图数据

解决地上/地下样地物种异同识别及韦恩图数据提取问题

先纠正初始代码的问题

你原来的代码里,用c(Year, Layer, Species)创建数据框是错误的,这会把三个向量拼成一个长向量,而非二维数据框。另外unique(Layer = Species)的语法也不符合函数要求,unique()不支持这种参数写法。

正确实现步骤及代码

我们可以用基础R或dplyr完成需求,核心是借助集合运算函数提取共有/独有物种:

1. 正确构造数据框

# 字符类型数据要加引号,避免被识别为未定义变量
Year <- c(2013, 2013, 2013, 2013, 2013, 2013, 2013, 2013)
Layer <- c("aboveground", "aboveground", "aboveground", "aboveground", 
           "belowground", "belowground", "belowground", "belowground")
Species <- c("ACTA", "ARTR", "RUBUS", "VITIS", "BOCY", "RUBUS", "VIOLA", "VITIS")

# 创建标准数据框
df <- data.frame(Year, Layer, Species)

2. 提取目标年份的物种集合

以2013年为例,先拆分地上、地下的物种(去重,排除同一物种的重复观测):

# 筛选2013年数据
df_2013 <- df[df$Year == 2013, ]

# 提取去重后的地上、地下物种集合
above_sp <- unique(df_2013[df_2013$Layer == "aboveground", "Species"])
below_sp <- unique(df_2013[df_2013$Layer == "belowground", "Species"])

3. 计算共有及独有物种

用基础R的集合函数直接计算:

# 两地共有物种
shared_sp <- intersect(above_sp, below_sp)
# 地上独有物种
above_only <- setdiff(above_sp, below_sp)
# 地下独有物种
below_only <- setdiff(below_sp, above_sp)

# 输出结果查看
cat("共有物种:", paste(shared_sp, collapse = ", "), "\n")
cat("地上独有物种:", paste(above_only, collapse = ", "), "\n")
cat("地下独有物种:", paste(below_only, collapse = ", "), "\n")

运行后会得到你示例中的结果:

共有物种: RUBUS, VITIS
地上独有物种: ACTA, ARTR
地下独有物种: BOCY, VIOLA

4. 直接用于韦恩图的数据

如果要制作韦恩图,多数R包(比如VennDiagram)只需集合元素或元素数量,直接用上面的above_sp、below_sp或三个子集即可。示例代码:

library(VennDiagram)
draw.pairwise.venn(
  area1 = length(above_sp),
  area2 = length(below_sp),
  cross.area = length(shared_sp),
  category = c("地上样地", "地下样地"),
  fill = c("#FF9999", "#9999FF"),
  print.mode = c("raw", "percent")
)

用dplyr的实现方式(适配tidyverse语法)

library(dplyr)

df_2013 <- df %>% 
  filter(Year == 2013) %>% 
  distinct(Layer, Species)

# 拆分物种集合
above_sp <- df_2013 %>% filter(Layer == "aboveground") %>% pull(Species)
below_sp <- df_2013 %>% filter(Layer == "belowground") %>% pull(Species)

# 后续集合计算和基础R方法一致
shared_sp <- intersect(above_sp, below_sp)
above_only <- setdiff(above_sp, below_sp)
below_only <- setdiff(below_sp, above_sp)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 07:15:26