Finding rows in R dataframe where a column value follows a sequence

前端 未结 2 1780
攒了一身酷
攒了一身酷 2021-01-22 16:55

I have a dataframe as below which is an output of a classifier.

col1, class
 123, 2
 122, 5
 124, 7
 125, 9
 126, 15
 127, 2
 128, 19
 129, 5
 130, 7
 179, 9
 18         


        
2条回答
  •  有刺的猬
    2021-01-22 17:35

    We can use shift from data.table, then paste the elements together and check where we have 579

    n <- 3
    library(data.table)
    setDT(df1)[, which(do.call(paste0, shift(class, seq(n)-1, type = "lead"))=="579")]
    #[1] 2 8
    

    Or instead of paste we can use Map with Reduce

    setDT(df1)[,  which(Reduce(`&`, Map(`==`, shift(class, seq(n)-1, 
                 type = "lead"), c(5, 7, 9))))]
    #[1] 2 8
    

提交回复
热议问题