【问题标题】:How to find the position of the first non-NA element in a column starting with the last element in an xts object如何从 xts 对象中的最后一个元素开始查找列中第一个非 NA 元素的位置
【发布时间】:2021-05-08 20:54:40
【问题描述】:
> 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 它只评估直到找到匹配项。

【问题讨论】:

    标签: r xts


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2017-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-11
      • 2021-09-28
      • 1970-01-01
      • 2019-09-02
      相关资源
      最近更新 更多