将数据转换为xts会更改时间戳数据

问题描述 投票:0回答:1

我目前正在研究土壤湿度,并且必须从我的时间序列数据中获得每小时和每日的平均值。

当我将数据帧转换为xts对象时,时间序列会发生变化,我无法弄清楚原因。

数据框中的数据如下所示:

  time                MC temp

1 2018-06-27 11:30:00 17.1 15.8

2 2018-06-27 11:45:00 17.0 15.8

3 2018-06-27 12:00:00 17.0 15.8

4 2018-06-27 12:15:00 17.0 15.9

5 2018-06-27 12:30:00 17.2 15.9

6 2018-06-27 12:45:00 17.0 16.0

但是当我转换它时,时间戳开始于2018-01-09 00:00并继续进行5分钟的时间增量。这是我正在使用的代码:

sm_xts <- xts(sm.data[,2:3], as.Date(sm.data$time))
sm_zoo <- read.zoo(sm.data, index.column = 1)
dat_xts <- as.xts(sm_zoo)

我已经将时间戳转换为as.POSIXct类,并在我的时间序列中检查重复项。

> anyDuplicated(sm.data$time)
[1] 0
r time-series xts
1个回答
0
投票

也许您的初始数据输入过程存在一些问题。

    df
#                  time   MC temp
# 1 2018-06-27 11:30:00 17.1 15.8
# 2 2018-06-27 11:45:00 17.0 15.8
# 3 2018-06-27 12:00:00 17.0 15.8
# 4 2018-06-27 12:15:00 17.0 15.9
# 5 2018-06-27 12:30:00 17.2 15.9
# 6 2018-06-27 12:45:00 17.0 16.0

现在,日期和时间值作为char存储在单个变量中

str(df$time)
# chr [1:6] "2018-06-27 11:30:00" "2018-06-27 11:45:00" ...

让我们将其转换为实际日期和时间,以免丢失时间信息:

strptime(df$time, "%Y-%m-%d %H:%M:%S")
# [1] "2018-06-27 11:30:00 EEST" "2018-06-27 11:45:00 EEST"
# [3] "2018-06-27 12:00:00 EEST" "2018-06-27 12:15:00 EEST"
# [5] "2018-06-27 12:30:00 EEST" "2018-06-27 12:45:00 EEST"

好像它有效。时区可能存在的问题超出了这个答案的范围。

现在让我们将数据帧转换为xts。在完成的xts中,我们不需要符号形式的日期和时间。所以我们排除第一列。

df2xts <- xts(df[,2:3], order.by=strptime(df$time, "%Y-%m-%d %H:%M:%S"))
df2xts
#                 time   MC temp
# 1 2018-06-27 11:30:00 17.1 15.8
# 2 2018-06-27 11:45:00 17.0 15.8
# 3 2018-06-27 12:00:00 17.0 15.8
# 4 2018-06-27 12:15:00 17.0 15.9
# 5 2018-06-27 12:30:00 17.2 15.9
# 6 2018-06-27 12:45:00 17.0 16.0
© www.soinside.com 2019 - 2024. All rights reserved.