且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

根据上一行的值选择特定的行(在同一列中)

更新时间:2022-12-10 08:08:43

对于第四个示例,您可以将which()dplyr中的lag()结合使用,以获得符合您条件的索引.然后,您可以使用它们来划分data.frame.

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