如何在以 xts 对象中的最后一个元素开始的列中找到第一个非 NA 元素的位置

How to find the position of the first non-NA element in a column starting with the last element in an xts object

> vols
               vol_tr     vol_yz     vol_cl    vol_iv
2021-01-22 0.06260922 0.09798388 0.09861034        NA
2021-01-25 0.09783596 0.10595096 0.10121109 0.1362547
2021-01-26 0.10485836 0.10672985 0.10117991 0.1388527
2021-01-27 0.08284200 0.10742612 0.09586469 0.1509771
2021-01-28 0.08452010 0.11046722 0.10247347 0.1229756
2021-01-29 0.07045891 0.11292108 0.10991404        NA

我想在列 vols$vol_iv 中找到第一个非 NA 的索引,从该列的末尾开始。我正在寻找索引或位置 5。要从 beginning 找到第一个非 NA,我可以这样做:

> d <- coredata(vols$vol_iv)
> pos = Position(function(d)!is.na(d), d)
> pos
[1] 2

Position 很好 b/c 它只会在找到匹配项之前进行评估。

Trim NA 使用 na.trim 关闭右端,然后取其长度来找到位置(或者使用 end 代替 length 如果你想要最后一个非 NA 值的时间)。

library(xts)

x <- xts(c(NA, 1, 2, 3, 4, NA), as.Date("2000-01-01")+0:5) # test input

length(na.trim(x, sides = "right"))
## [1] 5

要同时获取开始和结束的位置,或者如果您需要时间,则只使用 rng

rng <- range(time(na.trim(x)))
match(rng, time(x))
## [1] 2 5