根据值从 xts 对象中提取日期

Extracting Dates from xts object based on vaule

我想提取 xts 对象出现值变化的日期,即 A 的值从 1 变为 0 或从 0 变为 1 的日期:

require(xts)
A <- xts(c(1,1,0,0,1,1,0,0,1,1), Sys.Date()-10:1)
colnames(A) <- c("A")

> A
           A
2014-12-27 1
2014-12-28 1
2014-12-29 0
2014-12-30 0
2014-12-31 1
2015-01-01 1
2015-01-02 0
2015-01-03 0
2015-01-04 1
2015-01-05 1

想要的结果看起来像这样

> from.one.to.zero
[1] "2014-12-29" "2015-01-02"

> from.zero.to.one
[1] "2014-12-31" "2015-01-04"

你可以试试

index(A[diff(A)<0])
#[1] "2014-12-31" "2015-01-04"

index(A[diff(A)==1])
#[1] "2014-12-29" "2015-01-02"