I have a data frame as below. I want to first group the data frame by ID and Region, then filter the data frame by Content. I want to keep ID-Region pair that only have both 'High' and 'Mid' in the Content column.
My current data frame:
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))
My expect data frame:
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))
I try the following code, but I cannot keep ID-Region pair that only have both 'High' and 'Mid'.
newdata = data %>%
group_by(ID,Region) %>%
filter(n() != 1 & any(Content == "High") & any(Content == "Mid") & any(Content != "Low") %>%
ungroup