在 R 中使用 rollmax 函数时如何获取列的索引

How to get the index of a column when using rollmax function in R

我用这个函数在一个大小为100的滑动window中求最大值,除了求最大值,我还想从“open_time”中获取时间window中最大值对应的列。如何正确获取这个值?

library(data.table)
library(zoo)
library(binancer)

data <- binance_klines(symbol = 'ETHUSDT', interval = '1h', limit = 1000)[,1:5]
data <- data.table(data, rollingMax = rollmax(x = data$high, k = 100, na.pad = T, align = 'right'))

你可以试试这个:

library(data.table)
library(zoo)

setDT(data)

k <- 100
data[,  rollingMax := rollmaxr(high, k, fill = NA)]
data[,  roll_open_time := open_time[seq_len(.N) + 
                          rollapplyr(high, k, which.max, fill = NA) - k]]
data

使用 k = 3 在示例数据集上进行了尝试:

set.seed(123)
data <- data.frame(high = sample(10), open_time = rnorm(10))

setDT(data)
k <- 3
data[,  rollingMax := rollmaxr(high, k, fill = NA)]
data[, roll_open_time := open_time[seq_len(.N) + 
               rollapplyr(high, k, which.max, fill = NA) - k]]
data

#    high  open_time rollingMax roll_open_time
# 1:    3 -1.2650612         NA             NA
# 2:   10 -0.6868529         NA             NA
# 3:    2 -0.4456620         10     -0.6868529
# 4:    8  1.2240818         10     -0.6868529
# 5:    6  0.3598138          8      1.2240818
# 6:    9  0.4007715          9      0.4007715
# 7:    1  0.1106827          9      0.4007715
# 8:    7 -0.5558411          9      0.4007715
# 9:    5  1.7869131          7     -0.5558411
#10:    4  0.4978505          7     -0.5558411