根据 R 中两个数据帧的 presence/absence 值对列进行变异

Mutate a column based on the presence/absence of values from two data frames in R

我希望根据 Sales 列中的值改变一个名为 ClassType 的新列。

我的数据如下:

df <- data.frame(Group = c("A","A","A","A","A","B","B","B"),Sales = c("Bread","Bread","Milk","Milk","Bread","Cheese","Egg","Egg"), ClassType = c("Class1","Class1","Class1","Class1","Class1","Class2","Class2","Class2"))

我有两个字符向量 x 和 y

x <- c("Bread","Milk") 
y <- c("Egg","Cheese","Rice")

我的objective:

在组内,如果 Sales 的任何值包含 x 的任何值和 y 的值的 none,则 Class1,如果有的话Sales 的值包含来自 x 的任何值和来自 y 的任何值然后 Class2.

我已经用 any() 和 data.table::%in% 函数尝试了 case_when 和 if_else 语句,但我无法使 mutate 起作用

z <- df %>% group_by(Group) %>% mutate(ClassType = case_when(Sales == any(x) ~ "Class1",TRUE ~ "Class2"))

如有任何帮助,我们将不胜感激。

library(dplyr)

df %>% 
  group_by(Group) %>% 
  mutate(ClassType = case_when(
    any(Sales %in% x) & !any(Sales %in% y) ~ "Case 1",
    any(Sales %in% x) & any(Sales %in% y) ~ "Case 2",
    T ~ "Case 3"
  ))

输出

# A tibble: 8 x 3
# Groups:   Group [2]
  Group Sales  ClassType
  <chr> <chr>  <chr>    
1 A     Bread  Case 2   
2 A     Bread  Case 2   
3 A     Cheese Case 2   
4 A     Milk   Case 2   
5 B     Bread  Case 2   
6 B     Cheese Case 2   
7 B     Egg    Case 2   
8 B     Egg    Case 2