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

Viewed 78

I use the function to find the maximum in a sliding window of size 100, and in addition to finding the maximum, I would also like to get the time from the "open_time" column corresponding to the maximum value in the window. How to get this value correctly?

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'))
1 Answers

You can try this :

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

Tried this on sample dataset with 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
Related