2021年4月22日星期四

How can I identify the two smallest values (and indexes) rolling over a column in R?

I have been looking for an answer to this question for days. I think I am very close, but I cannot figure how to do the rolling piece of it.

I have a data.table with two columns like this:

df = data.table(a = c(8,3,6,12,15,21,4,5,1,32,13), b = c(12,3,1,66,4,7,32,6,76,2,11))    

I would like to obtain the smallest two values and their indexes on a rolling four day window. Rfast::nth seems to give me everything I need except I cannot vectorize it. Obviously I am doing something wrong.

I need the output to look as follows:

     a  b low lowIdx low2 low2Idx   1:  8 12  NA     NA   NA      NA   2:  3  3  NA     NA   NA      NA   3:  6  1  NA     NA   NA      NA   4: 12 66   3      2    6       3   5: 15  4   3      1    6       2   6: 21  7   6      1    12      2   7:  4 32   4      4    12      1   8:  5  6   4      3    4       3   9:  1 76   1      4    4       2  10: 32  2   1      3    4       1  11: 13 11   1      2    5       1  

I have attempted this with different forms of the following:

n <- nrow(df)  df$low[4:n] <- Rfast::nth(df[(n-3):n]$a, 1)  df$lowIdx[4:n] <- Rfast::nth(df$a, 1, index.return = TRUE)  df$low2[4:n] <- Rfast::nth(df[(n-3):n]$a, 2)  df$low2Idx[4:n] <- Rfast::nth(df$a, 2, index.return = TRUE)  

I have also been trying to work with the frollapply, but to no avail.

Thank you, Pete

https://stackoverflow.com/questions/67223775/how-can-i-identify-the-two-smallest-values-and-indexes-rolling-over-a-column-i April 23, 2021 at 11:51AM

没有评论:

发表评论