Reputation: 3088
I have a data.frame that looks like this.
dat1=data.frame(time=c(1,2,1,2,1,2,1,2), team=c("A","A","A","A","B","B","C","C"), name=c("LT","LT","CH","CH","CH","CH","AT","AT"))
time team name
1 A LT
2 A LT
1 A CH
2 A CH
1 B CH
2 B CH
1 C AT
2 C AT
I would like to say to dplyr, please, group_by "team" and filter the rows of each team that contains the name "LT". If a team does not contain the name "LT", then filter in the name "CH."
I would like my data.frame to look like this.
time team name
1 A LT
2 A LT
1 B CH
2 B CH
Any help is highly appreciated
Upvotes: 5
Views: 861
Reputation: 887078
We can arrange
first and then filter
based on the first
value in 'name' after grouping by 'team'
library(dplyr)
dat1 %>%
filter(name %in% c("LT", "CH")) %>%
arrange(team, ordered(name, levels = c('LT', 'CH'))) %>%
group_by(team) %>%
filter(name %in% first(name))
Upvotes: 2
Reputation: 39858
One dplyr
option could be:
dat1 %>%
group_by(team) %>%
filter(if(any(name == "LT")) name == "LT" else name == "CH")
time team name
<dbl> <fct> <fct>
1 1 A LT
2 2 A LT
3 1 B CH
4 2 B CH
Upvotes: 2