我有一个数据框,如下所示.我想先按ID和区域对数据帧进行分组,然后按内容过滤数据帧.我想保留在内容列中同时包含"高"和"中"的ID区域对.
我当前的数据帧:
structure(list(ID = c("a", "a", "a", "a", "a", "b", "b", "c",
"c", "c", "c", "d", "d", "d"), Content = c("High", "Mid", "Low",
"High", "Mid", "High", "Mid", "High", "Mid", "High", "Mid", "High",
"Mid", "Low"), Count = c("3", "6", "2", "3", "7", "3", "5", "8",
"5", "4", "2", "4", "9", "5"), Region = c("East", "East", "East",
"West", "West", "East", "East", "East", "East", "West", "West",
"West", "West", "West")), class = "data.frame", row.names = c(NA,
-14L))
我的expect数据帧:
structure(list(ID = c("a", "a", "b", "b", "c", "c", "c", "c"),
Content = c("High", "Mid", "High", "Mid", "High", "Mid",
"High", "Mid"), Count = c("3", "7", "3", "5", "8", "5", "4",
"2"), Region = c("West", "West", "East", "East", "East",
"East", "West", "West")), class = "data.frame", row.names = c(NA,
-8L))
我try 了下面的代码,但我不能保留同时具有"High"和"Mid"的ID-Region对.
newdata = data %>%
group_by(ID,Region) %>%
filter(n() != 1 & any(Content == "High") & any(Content == "Mid") & any(Content != "Low") %>%
ungroup