首页 > 解决方案 > 如何有条件地选择时间序列

问题描述

假设我有一个时间序列对象 B_ts。有些系列可能需要差分以使它们静止,而其他系列可能不需要。我想对所有系列执行增强的 Dickey-Fuller 测试,并仅将 diff(x) 应用于那些从 DF 测试中产生 p 值 > 0.05 的测试统计量的系列。p 值已经 < 0.05 的系列我希望保持“不变”。

有没有办法在 R 中做到这一点?

到目前为止,我为时间序列对象 B_ts 提供了以下代码:

B_ts <- ts(B) 

tseries::adf.test(B_ts) 

f1 = function(x){return(diff(x))}

C <- apply(B_ts,1, f1) #but only to rows that require differencing!

tseries::adf.test(C) #to see whether p value for all time series is now < 0.05 after differencing

非常感谢!

标签: rtime-seriesdifference

解决方案


这是一种进行一次的方法,请lapply注意,第二个系列的最终 p 值为 0.065,因此取决于您遇到的问题和您的数据,您可能希望多次滞后。

# To choose example ts data 
# data()
tseries <- list("t1" = AirPassengers, "t2" = BJsales) ;

# apply your test to the list of series
adf <- lapply(tseries, function(x) tseries::adf.test(x)$p.value)

# index only series that need diff
diff_index <- which(adf > 0.05)
tseries_diff <- tseries ;
tseries_diff[diff_index] <- lapply(tseries_diff[diff_index], diff) ;

# verify
adf <- lapply(tseries_diff, function(x) tseries::adf.test(x)$p.value)
adf

# choose if you want to iterate again / or if your want to find a smarter lag

推荐阅读