Reputation: 1324
When I filter a dataframe where the condition is made up of other filters, it doesn't seem to work. However, if I store the condition as a variable (f
in the example), the filtering works fine. Can someone explain why this happens, and how to make something like Example 2 work? I would prefer to not store the filter condition as a variable.
library(dplyr)
# Dummy data set
df <- data.frame(Country = factor(c("Argentina", "Brazil", "Brazil", "Brazil")),
Type = factor(c("A", "A", "B", "C")))
# Only returns Brazil. No problem here.
f <- df %>%
group_by(Country) %>%
summarise(nTypes = n_distinct(Type)) %>%
filter(nTypes==3) %>%
select(Country) %>%
droplevels() %>%
unlist()
# > f
# Country
# Brazil
# Levels: Brazil
# Example 1 - Only returns rows of df where Country=="Brazil". No problem here.
df %>% filter(
Country %in% (f
)
)
# Country Type
# 1 Brazil A
# 2 Brazil B
# 3 Brazil C
# Example 2 - Filter is equivalent to `f` but returns all rows of df, not just Brazil. No idea why!
df %>% filter(
Country %in% (df %>%
group_by(Country) %>%
summarise(nTypes = n_distinct(Type)) %>%
filter(nTypes==3) %>%
select(Country) %>%
droplevels() %>%
unlist()
)
)
# Country Type
# 1 Argentina A
# 2 Brazil A
# 3 Brazil B
# 4 Brazil C
Upvotes: 1
Views: 295
Reputation: 6325
While I'm not sure why you are getting unexpected results, based on this answer: Using filter inside filter in dplyr gives unexpected results a way to get desired result after filter
ing is to use inner_join
df %>%
group_by(Country) %>%
summarise(nTypes = n_distinct(Type)) %>%
filter(nTypes==3) %>%
select(Country) %>% inner_join(.,df)
Output:
Joining, by = "Country"
# A tibble: 3 x 2
Country Type
<fctr> <fctr>
1 Brazil A
2 Brazil B
3 Brazil C
Upvotes: 1