【发布时间】:2021-10-15 08:13:03
【问题描述】:
我正在处理时间序列数据,需要能够按周对其进行排序才能创建分面图。使用以下代码,我根据 Date_time 列创建了一个包含一年中周数的列:
#Creates the Date_time column
target_detections_all_15E$Date_time <- as.POSIXct(paste(as.Date(as.character(target_detections_all_15E$Ping_date),"%Y-%m-%d"), target_detections_all_15E$Ping_time, sep=" "),format = "%Y-%m-%d %H:%M:%S", tz="Asia/Bangkok")
#eliminates zeroes in the data
target_detections_all_15E<- target_detections_all_15E[target_detections_all_15E$TS_comp !=-9.9e+37,]
#Formats the time to create the Week column and is supposed to change the week numbers to a sequence that starts at 1.
target_detections_all_15E$Week <- as.integer(format(target_detections_all_15E$Date_time, "%V"))
target_detections_all_15E<- transform(target_detections_all_15E, Week=Week-min(Week)+1)
代表数据:
Ping_date Ping_time Date_time Week
1 2020-12-01 18:14:54 2020-12-01 18:14:54 49
2 2020-12-01 18:14:54 2020-12-01 18:14:54 49
3 2020-12-01 18:14:54 2020-12-01 18:14:54 49
4 2020-12-07 00:14:55 2020-12-07 00:14:55 50
5 2020-12-07 00:14:55 2020-12-07 00:14:55 50
6 2020-12-07 00:14:55 2020-12-07 00:14:55 50
7 2020-12-14 18:14:56 2020-12-14 00:14:56 51
8 2020-12-14 18:14:56 2020-12-14 00:14:56 51
9 2020-12-14 18:14:56 2020-12-14 00:14:56 51
10 2020-12-14 18:14:56 2020-12-14 00:14:56 51
我的问题是星期列中生成的数字是基于日期的,并在 2020 年 12 月 7 日更改为“50”。我的数据从 2020-12-01 18:14:54 开始,我希望周数由时间范围决定,在这种情况下,在初始开始时间之后 168 小时,因此第一周结束时变为 2020-12- 08 18:14:54。我需要进行设置,以便在 168 小时后“周”列显示为“1”,然后切换为“2”。
所需数据集示例:
Ping_date Ping_time Date_time Week
1 2020-12-01 18:14:54 2020-12-01 18:14:54 1
2 2020-12-01 18:14:54 2020-12-01 18:14:54 1
3 2020-12-01 18:14:54 2020-12-01 18:14:54 1
4 2020-12-08 18:14:55 2020-12-08 18:14:55 2
5 2020-12-08 18:14:55 2020-12-08 18:14:55 2
6 2020-12-08 18:14:55 2020-12-08 18:14:55 2
7 2020-12-15 18:14:56 2020-12-15 18:14:56 3
8 2020-12-15 18:14:56 2020-12-15 18:14:56 3
9 2020-12-15 18:14:56 2020-12-15 18:14:56 3
10 2020-12-15 18:14:56 2020-12-15 18:14:56 3
【问题讨论】:
-
另一个类似的选项是以小时为单位的差值除以 168。
Week = as.integer(floor(difftime(Date_time, min(Date_time), units = 'hours')/168)))