Select specific rows based on previous row value (in the same column)

前端 未结 2 856
滥情空心
滥情空心 2021-01-06 16:54

I\'ve been trying to figure a way to script this through R, but just can\'t get it. I have a dataset like this:

Trial  Type Correct Latency     
1       55          


        
2条回答
  •  梦毁少年i
    2021-01-06 17:46

    For the fourth example, you could use which() in combination with lag() from dplyr, to attain the indices that meet your criteria. Then you can use these to subset the data.frame.

    # Get indices of rows that meet condition
    ind2 <- which(df$Type==20 & dplyr::lag(df$Type)==40)
    # Get indices of rows before the ones that meet condition
    ind1 <- which(df$Type==20 & dplyr::lag(df$Type)==40)-1
    
    # Subset data
    > df[c(ind1,ind2)]
       Trial Type Correct Latency
    1:    28   40       1     500
    2:    29   20       1     230
    

提交回复
热议问题