簡體   English   中英

將1和0組為兩個詞組,標識開始和結束並計算持續時間

[英]Group 1's and 0's into two phrases, identify start and end, and count duration

我正在做一些周期性分析。

我有變量X,如果處於收縮狀態,則為true,否則為false

X
##[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

....

我改成0和1

X2<-as.ts(X*1)

然后我有一個日期序列。

td
## [1] "2000-01-31" "2000-02-29" "2000-03-31" "2000-04-30" "2000-05-31" "2000-06-30"

....

然后我用'zoo'以td順序索引X2

library(zoo)
na_ts = zoo(x=X2, order.by=td) 

現在是我的問題。 我想確定值更改時的日期,並計算該系列停留在1和0的時間。

如此理想的結果:

start      end          type       duration
2000-01-31 - 2001-05-31 contraction 17 months
2001-06-30 - 2004-05-31  expansion .... 

有人可以幫我嗎? 提前謝謝了。

您可以使用X的游程編碼將時間序列分成具有相同值的連續元素:

# Reproducible example
X <- c(F, F, F, T, T, F)
td <- c( "2000-01-31", "2000-02-29", "2000-03-31", "2000-04-30", "2000-05-31", "2000-06-30")
library(zoo)
na_ts = zoo(x=X, order.by=td)

# Split with run-length encoding
runlens <- rle(X)
(ts.spl <- split(na_ts, rep(seq_along(runlens$lengths), times=runlens$lengths)))
# $`1`
# 2000-01-31 2000-02-29 2000-03-31 
#      FALSE      FALSE      FALSE 
# 
# $`2`
# 2000-04-30 2000-05-31 
#       TRUE       TRUE 
# 
# $`3`
# 2000-06-30 
#      FALSE 

現在,您可以從存儲在ts.spl列表中的每個時間序列中提取所需的任何信息。 例如:

dat <- data.frame(start = sapply(ts.spl, start),
                  end = sapply(ts.spl, end),
                  val = ifelse(runlens$values, "contraction", "expansion"))
dat$days <- as.numeric(as.Date(dat$end) - as.Date(dat$start), units="days")
dat
#        start        end         val days
# 1 2000-01-31 2000-03-31   expansion   60
# 2 2000-04-30 2000-05-31 contraction   31
# 3 2000-06-30 2000-06-30   expansion    0

這種方法是“拆分應用合並”的一個示例,其中我們根據數據的某些屬性拆分原始數據,應用函數提取有關每個片段的感興趣信息,然后將其重新組合在一起。

這是我稍加修改后的代碼。 謝謝josilber! 我們通常會在周期性分析中處理月度數據,因為約會長達數天並不准確。 同樣,經濟可能處於衰退/擴張中,因此不會為零。

na_ts = zoo(x=X, order.by=td)

# Split with run-length encoding

runlens <- rle(X)
(ts.spl <- split(na_ts, rep(seq_along(runlens$lengths), times=runlens$lengths)))

dat <- data.frame(start = sapply(ts.spl, start),
                  end = sapply(ts.spl, end),
                  val = ifelse(runlens$values, "contraction", "expansion"))
dat$months<- runlens$lengths
dat

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM