How to filter pair of rows based on two ordered values

I'm working on a French historical census and I'm looking to filter married couples. In my data, a married couple is a male followed by a demale (always in this order). There are also other members.

        id <- c(1:10)
        members <- c("male", "male", "female", "male", "female", "male", "children", "cousin", "female", "male") 

        household <- data.frame(id, members)  
        household

        library(dplyr)
        married_couples <- household %>%
          filter(members == "male", lead(members) =="female" )
        married_couples


           id  members
           1     male
           2     male
           3   female
           4     male
           5   female
           6     male
           7 children
           8   cousin
           9   female
          10     male

What I want :

           id  members
           2     male
           3   female
           4     male
           5   female

I tried without succes :

library(dplyr)
married_couple <- household %>%
filter(members == "male", lead(members) =="female" )
married_couple


Read more here: https://stackoverflow.com/questions/66998395/how-to-filter-pair-of-rows-based-on-two-ordered-values

Content Attribution

This content was originally published by Wilcar at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: