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

如何在R中按组检查指定值是否存在并输出明细结果

检查分组中指定值的存在情况(以iris数据集为例)

需求:检查每个Species分组是否包含Petal.Length为1、3、4的值,输出一个数据集展示每个待检查值在各分组中的存在情况(而非汇总每组是否包含所有指定值)。

用户尝试的代码

# 加载示例数据
data(iris)

# 预览数据
> head(iris)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

# 指定待检查值
expected_values <- c(1, 3, 4)

# 尝试的方法:仅返回每组是否包含所有指定值的汇总
result <- iris %>%
  group_by(Species) %>%
  summarise(
    all_values_present = all(expected_values %in% Petal.Length)
  ) %>%
  ungroup()

> print(result)
# A tibble: 3 × 2
  Species    all_values_present
  <fct>      <lgl>             
1 setosa     FALSE             
2 versicolor FALSE             
3 virginica  FALSE            

目标输出

Species Petal.Length value_is_present
     setosa            1                Y
 versicolor            1                N
  virginica            1                N
     setosa            3                N
 versicolor            3                Y
  virginica            3                Y
     setosa            4                N
 versicolor            4                N
  virginica            4                N

解决方案代码

通过生成分组与指定值的笛卡尔积,再和原数据的分组去重值做左连接,最后判断存在性:

library(dplyr)
library(tidyr)

data(iris)
expected_values <- c(1, 3, 4)

# 生成所有Species和待检查值的组合
species_values <- expand_grid(
  Species = unique(iris$Species),
  Petal.Length = expected_values
)

# 提取每个Species中存在的Petal.Length
existing_values <- iris %>%
  group_by(Species) %>%
  distinct(Petal.Length) %>%
  mutate(value_is_present = TRUE)

# 左连接并转换为Y/N标记
final_result <- species_values %>%
  left_join(existing_values, by = c("Species", "Petal.Length")) %>%
  mutate(value_is_present = ifelse(is.na(value_is_present), "N", "Y")) %>%
  arrange(Petal.Length, Species)

print(final_result)

输出结果

# A tibble: 9 × 3
  Species    Petal.Length value_is_present
  <fct>             <dbl> <chr>           
1 setosa                1 Y               
2 versicolor            1 N               
3 virginica             1 N               
4 setosa                3 N               
5 versicolor            3 Y               
6 virginica             3 Y               
7 setosa                4 N               
8 versicolor            4 N               
9 virginica             4 N               

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 03:42:17