在时间序列中,找到满足条件的最长后续时间段

In a time series, find the longest subsequent period for which a condition is met

我需要搜索dataframe,如下: 如果成绩在时间 = 1 时超过 50%,然后在时间 = 3 时低于 50%,然后在时间 = 4 时高于 50%,在时间 = 7 时低于 50%,然后在时间 8 时达到,在时间 12 时低于 50%,依此类推。 ...然后它在上方持续 2 秒,然后是 3 秒,然后是 4 秒,等等。 ...所以最终所需的结果是超过 50% 的最大时间,在这种情况下为 4 秒(根据下面的数据框部分)。 所以我需要将 4 的值分配给 max(maxGradeTimePeriod) 请问这个简单的代码?提前致谢。

这是我迄今为止尝试过的方法(多次尝试中的 1 次!):

    maxGradeTimePeriod <- c()
    i <- 1

    while (i <= nrow(df)) {
            if (0.5 <= df$Grade[i]) {
                    p <- i+1
                    k <- p
                    while (k < (nrow(df)-1)) {
                            if (df$Grade[k] < 0.5) {
                                    time <- (df$Time[k-1])-df$Time[i]
                                    print(time)
                                    maxGradeTimePeriod <- append(maxGradeTimePeriod, time)
                            }
                            else {
                                    time <- max(df$Time)-df$Time[i]
                                    maxGradeTimePeriod <- append(maxGradeTimePeriod, time)
                                                                            }
                            k <- k+1
                            }
                    }
                    i <- i+1
            }
            else {
                    i <- i+1
            }
    }

示例数据框:

 time grade
    1   0.5
    2   0.5
    3   0.1
    4   0.5
    5   0.5
    6   0.5
    7   0.1
    8   0.5
    9   0.5
   10   0.5
   11   0.5
   12   0.1
   13   0.5
   14   0.5
   15   0.5
   16   0.1
   17   0.5
   18   0.5
   19   0.1
   20   0.5

假设每一行是一个时间单位,尝试:

y <- rle(x$grade >= 0.5)              # Find clusters of values not below 0.5
max(y$length[which(y$values)])        # Find which TRUE cluster is the largest
# [1] 4

可能是时间点间距不均匀。在这种情况下,请尝试:

x2 <- rle(x$grade >= 0.5)$length      # Get all clusters
x3 <- rep(seq_along(x2), x2)          # Make a vector that specifies cluster per value
time <- c(0, diff(x$time))            # Make a new vector with time differences 
y <- aggregate(time ~ x3, FUN=sum)    # Aggregate the sum of time per cluster
max(y$time)                           # Take the max
# [1] 4