如何创建时间序列对象yyyy-mm-dd hh:mm:ss?

时间:2018-02-15 14:45:54

标签: r time-series

我正在尝试将声音数据转换为时间序列对象,以便进一步分析它(使用来自' bspec'包的f.ex. WelchPSD)。我的数据频率为25811个样本/秒(Hz)。

我的声音文件s2_d

> str(s2_d)
 int [1:52422753] -442 -434 -428 -413 -389 -386 -382 -387 -403 -373 ...

是从包信号中的Waveread创建的Wave对象中提取数据后的整数。

文件开始和结束:

> begin <- as.POSIXct("2017-08-17 17:04:34", tz="UTC")

> end <- as.POSIXct("2017-08-17 17:38:25", tz="UTC")

我尝试使用以下行将s2_d转换为ts:

> s2_dts <- ts(s2_d, start = as.numeric(begin), end = as.numeric(end), frequency = 25811)

> s2_dts <- as.ts(s2_d, start = as.numeric(begin), end = as.numeric(end), frequency = 25811)

> s2_dts <- ts(s2_d, start = as.numeric(as.POSIXct(begin)), end = as.numeric(as.POSIXct(end)), frequency = 25811)

> s2_dts <- as.ts(s2_d, start = as.numeric(as.POSIXct(begin)), end = as.numeric(as.POSIXct(end)), frequency = 25811)

他们都将s2_d转换为ts

> class(s2_dts)
[1] "ts"
> start(s2_dts)
[1] 1502989474          1

但是当我尝试使用函数窗口()时,我无法提取f.ex.我的时间序列中有1秒的片段,所以事情并不完全正确。

> x <- window(s2_dts, start = as.numeric(begin), end = as.numeric("2017-08-17 17:04:35"), extend= TRUE)
Error in if (start > end) stop("'start' cannot be after 'end'") : 
  missing value where TRUE/FALSE needed
In addition: Warning message:
In window.default(x, ...) : NAs introduced by coercion

我终于尝试过了:

> s2_dts <- ts(s2_d, start = c(2017,8,17,17,04,34), end = c(2017,8,17,17,38,25), frequency = 25811)

> start(s2_dts)
[1] 2017    8

> time(s2_dts)
Time Series:
Start = c(2017, 8) 
End = c(2017, 8) 
Frequency = 25811 [1] 2017

这是更好的,即使只有年和月被认可。如何将包括日,小时,分钟和秒在内的整个时间作为时间序列的开始时间?

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

data <- runif(10, 1, 10) # mock data
> data
[1] 9.455453 4.596560 9.675503 7.437548 2.722311 7.729820 5.737903 2.540364 3.512660 5.555681

# 2 samples/second 
begin <- as.POSIXct("2017-08-17 17:04:34", tz="UTC")
end <- as.POSIXct("2017-08-17 17:04:39", tz="UTC")

# Create time-series object
df_ts <- ts(data, 
            start = as.numeric(begin), 
            end = as.numeric(end), 
            frequency = 2)

> window(df_ts, 
         start = as.numeric(begin), 
         end = as.numeric(as.POSIXct("2017-08-17 17:04:36", tz="UTC")))
Time Series:
Start = c(1502989474, 1) 
End = c(1502989476, 1) 
Frequency = 2 
[1] 9.455453 4.596560 9.675503 7.437548 2.722311