如何将毫秒数据转换为R中的时间序列

时间:2018-06-08 07:10:01

标签: r time-series posixct

timeInMSec height  c1
  1     100.0   1
  5     80.0    1
  6     80.0    0
  9     76.0    1
 12     80.5    0
 14     80.5    1
 16     80.5    0

我有如上所示的数据,其中timeInMsec是以毫秒为单位的时间,每当发生变化时我们记录数量。数量是类和连续值,所以我想对这类数据进行时间序列分析。 那么如何使用R?

将这种不规则数据转换为时间序列

1 个答案:

答案 0 :(得分:2)

你提到过"每当发生变化时我们记录数量",所以你可以扩展系列,然后根据之前的观察结果填充值。之后,您可以将数据框转换为时间序列。如果您正在寻找更先进的插补技术。您可以考虑imputeTS包中的功能。

library(tidyverse)

dat2 <- dat %>%
  # Complete the sequence
  complete(timeInMSec = full_seq(timeInMSec, period = 1)) %>%
  # Fill the value based on previous record
  fill(-timeInMSec)

# Convert to ts object
dat_ts <- ts(dat2[, -1], start = dat2$timeInMSec[1], end = dat2$timeInMSec[16])

数据

dat <- read.table(text = "timeInMSec height  c1
  1     100.0   1
                  5     80.0    1
                  6     80.0    0
                  9     76.0    1
                  12     80.5    0
                  14     80.5    1
                  16     80.5    0",
                  header = TRUE)