Extract values based on conidtion of another column

前端 未结 2 520
梦谈多话
梦谈多话 2021-01-29 11:25
case_number <- c(\"1\", \"1\", \"2\", \"2\", \"2\", \"3\", \"3\") 
type <- c(\"STD\", \"STD2\", \"STD\", \"STD3\", \"STD2\", \"STD\", \"STD2\") 
date <- as.Date         


        
2条回答
  •  借酒劲吻你
    2021-01-29 11:58

    Here's a shot:

    myfilter <- function(x) {
      r <- rle(x %in% c("STD", "STD2"))
      any(r$lengths[r$values] > 1)
    }
    
    library(dplyr)
    data %>%
      group_by(case_number) %>%
      filter(myfilter(type)) %>%
      ungroup()
    # # A tibble: 4 x 3
    #   case_number type  date      
    #               
    # 1 1           STD   2008-11-01
    # 2 1           STD2  2009-03-25
    # 3 3           STD   2015-03-14
    # 4 3           STD2  2015-04-15
    

    It does not care about order, just about finding either of them in a chain of two (or more).

提交回复
热议问题