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

前端 未结 2 1809
攒了一身酷
攒了一身酷 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: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))
    

提交回复
热议问题