将十进制日期转换为年和周数

时间:2019-03-31 11:47:30

标签: r

我正在运行一个Arima模型来预测库,该模型的输出包含以下内容:

+----------+----------------+------------+----------+-----------+----------+
|          | Point Forecast |   Lo 80    |  Hi 80   |   Lo 95   |  Hi 95   |
+----------+----------------+------------+----------+-----------+----------+
| 2016.261 |       335.0697 | 267.368566 | 402.7707 | 231.52977 | 438.6095 |
| 2016.281 |       346.7667 | 234.935713 | 458.5978 | 175.73594 | 517.7975 |
| 2016.300 |       296.3013 | 174.495528 | 418.1070 | 110.01547 | 482.5870 |
| 2016.319 |       379.0095 | 255.265230 | 502.7537 | 189.75899 | 568.2600 |
+----------+----------------+------------+----------+-----------+----------+

我想要实现的是通过添加两列来转换十进制日期(例如2016.261),其中一列代表年份,另一列代表星期数,实现如下所示:

+----------+---------+------+----------------+------------+----------+-----------+----------+
|          |  year   | week | Point Forecast |   Lo 80    |  Hi 80   |   Lo 95   |  Hi 95   |
+----------+---------+------+----------------+------------+----------+-----------+----------+
| 2016.261 |    20.. | n1   |       335.0697 | 267.368566 | 402.7707 | 231.52977 | 438.6095 |
| 2016.281 |    20.. | n1   |       346.7667 | 234.935713 | 458.5978 | 175.73594 | 517.7975 |
| 2016.300 |    20.. | n3   |       296.3013 | 174.495528 | 418.1070 | 110.01547 | 482.5870 |
| 2016.319 |    20.. | n4   |       379.0095 | 255.265230 | 502.7537 | 189.75899 | 568.2600 |
+----------+---------+------+----------------+------------+----------+-----------+----------+

1 个答案:

答案 0 :(得分:0)

好吧,例如这样的数据框:

df1 <- data.frame(x =c(2016.01, 2016.32, 2016.261, 2016.281 , 2016.300 , 2016.319))
df1$date <- as.Date(as.character(df1$x), format="%Y.%j")
df1$year <- format(df1$date, "%Y")
df1$week <- format(df1$date, "%W")
df1

#         x       date year week
# 1 2016.010 2016-01-01 2016   00
# 2 2016.320 2016-02-01 2016   05
# 3 2016.261 2016-09-17 2016   37
# 4 2016.281 2016-10-07 2016   40
# 5 2016.300 2016-01-03 2016   00
# 6 2016.319 2016-11-14 2016   46

注意:我添加了前两个日期只是为了检查日期是否正确。除了df1之外,您还可以使用数据框。所有信息实际上都来自here