如何在R中修复“ try.xts(x,error =“'x'必须基于时间或xtsible”)中的错误?

时间:2019-05-06 12:33:27

标签: r time-series

我正在尝试对Twitter上的数据集进行时间序列分析。我正在使用analalize库。在我的数据上运行它时,出现以下错误,这似乎表明timestamp_r列存在问题:

Android/data/

以下是产生错误的代码:

class SomeComponent {
  constructor(@Inject(DOCUMENT) document: any) {
  console.log(document.location.href);
}

这是数据集的一瞥:

Converting from tbl_df to tbl_time.
Auto-index message: index = timestamp_r
Error in try.xts(x, error = "'x' needs to be timeBased or xtsible") : 
  'x' needs to be timeBased or xtsible

我很乐意提供重现此问题所需的其他任何东西。

谢谢您的指导。

1 个答案:

答案 0 :(得分:1)

我有同样的问题。我最终通过编写一个可重现的示例解决了这个问题。我正在回答,希望对其他人有帮助(我第一次回答问题!)。

Anomalize Quick Start Guide中所述,包中的功能必须在tibbletime对象(类tbl_time)上执行。就您而言,该函数无法将您的数据对象转换为tibbletime对象。我怀疑这是由于您的datetime_r变量中的NA值所致。

这会产生转换错误

library(tidyverse) 
library(anomalize)

# Create some test data
count <- c(1:25, 40, 27:50, 25, 52:75, 105, 77:100)
datetime_r <- seq(from = as.POSIXct('2013-01-01 00:00'), by = "1 hour", length.out = 100) 

# Insert an NA value into the datetime variable
datetime_r[25] <- NA

# Create a tibble object
test <- tibble(count, datetime_r)

# Run the amonalize function
test %>%
    # Data Manipulation / Anomaly Detection
    time_decompose(count) %>%
    anomalize(remainder, alpha = 0.05, max_anoms = 0.2) %>%
    time_recompose() %>%
    # Anomaly Visualization
    plot_anomalies(time_recomposed = TRUE) +
    labs(title = "Anomalies for Test Data") 

错误消息

Converting from tbl_df to tbl_time.
Auto-index message: index = datetime_r
Error in try.xts(x, error = "'x' needs to be timeBased or xtsible") : 
  'x' needs to be timeBased or xtsible

从datetime变量中删除NA值,然后重新运行该函数

count <- c(1:25, 40, 27:50, 25, 52:75, 105, 77:100)
datetime_r <- seq(from = as.POSIXct('2013-01-01 00:00'), by = "1 hour", length.out = 100) 

test <- tibble(y, datetime_r)

saved <- test %>%
    time_decompose(count) %>%
    anomalize(remainder, alpha = 0.05, max_anoms = 0.2) %>%
    time_recompose() %>%
    plot_anomalies(time_recomposed = TRUE) +
    labs(title = "Anomalies for Test Data")

这次没有错误。

这将生成下图,以可视化的方式识别该功能。

Anomaly detection figure for test data

对保存的数据进行分组,以检查被识别为异常的观测结果。

saved$data[saved$data$anomaly == "Yes",]

# A time tibble: 4 x 10
# Index: datetime_r
  datetime_r          observed    season trend remainder remainder_l1 remainder_l2
  <dttm>                 <dbl>     <dbl> <dbl>     <dbl>        <dbl>        <dbl>
1 2013-01-02 01:00:00       40 -2.32e-15  26.0  1.40e+ 1    -1.58e-13     1.44e-13
2 2013-01-03 02:00:00       25 -7.79e-15  51.  -2.60e+ 1    -1.58e-13     1.44e-13
3 2013-01-04 03:00:00      105 -6.67e-15  76    2.90e+ 1    -1.58e-13     1.44e-13
4 2013-01-05 03:00:00      100 -6.67e-15 100.0  1.56e-13    -1.58e-13     1.44e-13
# ... with 3 more variables: anomaly <chr>, recomposed_l1 <dbl>, recomposed_l2 <dbl>