n最大值贬值

时间:2017-03-12 15:55:16

标签: r max

考虑具有以秒为单位的时间列和值列x的数据帧。 我试图找到x的n个最大值的索引,这些索引之间至少有一个lambda的时间。

例如,如果df如下:

time, x

1, 100
2, 95
4, 10
5, 100
7, 99
8, 98
10, 98
12, 10

查找以4秒分隔的3个最大值,nlargest(data = df, n = 3, lambda = 4)应返回1,5,10。

遗憾的是,我还没有找到一种聪明的方法。任何提示都会非常受欢迎!

2 个答案:

答案 0 :(得分:1)

您可以对值进行排序,然后使用diff函数检查索引是否足够远。

set.seed(42) 
lambda <- 4
n <- 3
df <- data.frame(time=1:20,x=sample(1:100,20))
df
#   time  x
#   1     1 92
#   2     2 93
#   3     3 29
#   4     4 81
#   5     5 62
#   6     6 50
#   7     7 70
#   8     8 13
#   9     9 61
#   10   10 65
#   11   11 42
#   12   12 91
#   13   13 83
#   14   14 23
#   15   15 40
#   16   16 80
#   17   17 88
#   18   18 10
#   19   19 39
#   20   20 46
o <- order(df$x,decreasing = TRUE) # get the order of values
# select values which indexes are far enough 
df$x[o[c(TRUE,abs(diff(df$time[o]))>lambda)]][1:n] 
# [1] 93 91 88
sort(df$x,dec=TRUE)[1:3]
# [1] 93 92 91

如您所见,仅使用sort函数返回93(第二个),然后是92(这是第一个)==太近了。

答案 1 :(得分:1)

如果time != 1:k(或time == 1:k),您可以

set.seed(94)
df     <- data.frame(time  = seq(1,200,2), x = sample(1:200))
n      <- 4
lambda <- 20

sorted <- df[order(-df$x),]
result <- sorted[1,]

i <- 1
while (nrow(result) < n){
    if (all(abs(sorted[i, 'time'] - result[, 'time']) >= lambda)) {
        result <- rbind(result, sorted[i,])
    }
    i <- i + 1
}

result[,2]
## [1] 200 199 198 196

min(abs(diff(result[order(result$time),'time']))) >= lambda
## [1] TRUE
相关问题