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

前端 未结 2 851
滥情空心
滥情空心 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条回答
  •  耶瑟儿~
    2021-01-06 17:50

    Here is an example code if you always want to delete the first trials of your data.

    var1 <- c(1,2,1,2,1,2,1,2,1,2)
    var2 <- c(1,1,1,2,2,2,2,3,3,3)
    
    dat <- data.frame(var1, var2)
    
    var1 var2
    1     1    1
    2     2    1
    3     1    1
    4     2    2
    5     1    2
    6     2    2
    7     1    2
    8     2    3
    9     1    3
    10    2    3
    
    #delete only this line directly
    filter(dat,lag(var2)==var2)
    
    var1 var2
    1     1    1
    2     2    1
    3     1    1
    6     2    2
    7     1    2
    10    2    3
    
    #delete the first 2 trials
    #make a list of all rows where var2[n-1]!=var2[n] --> using lag from dplyr
    drops <- c(1,2,which(lag(dat$var2)!=dat$var2), which(lag(dat$var2)!=dat$var2)+1)
    if (!identical(drops,numeric(0))) { dat <- dat[-drops,] }
    
    var1 var2
    3     1    1
    6     2    2
    7     1    2
    10    2    3
    

提交回复
热议问题