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

前端 未结 2 1779
攒了一身酷
攒了一身酷 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
    
    0 讨论(0)
  • 2021-01-22 17:37

    A somewhat more lengthy base R alternative, in principle similar to @akrun's answer:

    which(do.call(paste0, cbind(df1, with(df1, class[seq_along(class)+1]),
                                 with(df1, class[seq_along(class)+2]))[-1]) == "579")
    #[1] 2 8
    

    data:

    df1 <- structure(list(col1 = c(123L, 122L, 124L, 125L, 126L, 127L, 128L, 
                                   129L, 130L, 179L, 180L), class = c(2L, 5L,
                                   7L, 9L, 15L, 2L, 19L, 5L, 7L, 9L, 3L)),
                                  .Names = c("col1", "class"), class = "data.frame", 
                                   row.names = c(NA, -11L))
    
    0 讨论(0)
提交回复
热议问题