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

R语言分组筛选:仅保留含蓝/黄颜色的日期分组

筛选符合颜色规则的日期分组

目标

筛选所有仅包含蓝色或黄色的日期分组,规则如下:

  • 若分组含2种颜色,需同时为蓝色和黄色
  • 若仅含1种颜色,可为蓝色或黄色

示例数据集说明

  • 2024-01-01:因含紫色且有3种唯一颜色,被排除
  • 2024-03-27:仅含蓝色,符合要求
  • 2024-05-15:同时含蓝色和黄色,符合要求
  • 2024-06-08:因含橙色被排除,此情况的筛选逻辑待完善

现有代码

library(tidyverse)

dates <- c(rep("2024-01-01",3), "2024-03-27", rep("2024-05-15",2), rep("2024-06-08",2))
color <- c("blue","purple","yellow","blue","blue", "yellow", "yellow","orange")

df <- tibble(dates, color)
df


df %>% 
  group_by(dates) %>% 
  mutate(unique_colors_per_day = n_distinct(color)) %>% 
  ungroup() %>% 
  filter(unique_colors_per_day == 1 & color %in% c("blue", "yellow") |
           unique_colors_per_day == 2 & color "??????")

待完善内容

需完善上述filter语句中对应2种颜色情况的筛选逻辑,排除含蓝黄以外颜色的分组。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 18:04:55