我正在处理时间序列数据,需要能够按周对其进行排序,以便创建一个面图。使用以下代码,我根据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)
Reprex数据:
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-07年改为"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
发布于 2021-08-11 14:03:21
示例数据:
d <- tibble(Date_time = c("2020-12-01 18:14:54", "2020-12-08 18:14:55", "2020-12-15 18:14:56"))
# A tibble: 3 × 1
Date_time
<chr>
1 2020-12-01 18:14:54
2 2020-12-08 18:14:55
3 2020-12-15 18:14:56
difftime()
计算数据中每个日期到最小日期之间的周数(即第一天)。
floor()
获取整数(四舍五入)as.numeric()
将其强制转换为整数。
library(dplyr)
library(lubridate)
d <- tibble(Date_time = c("2020-12-01 18:14:54", "2020-12-08 18:14:55", "2020-12-15 18:14:56"))
d %>%
mutate(Date_time = as_datetime(Date_time, tz = "Asia/Bangkok"),
Week = as.numeric(floor(difftime(Date_time, min(Date_time), units = "weeks") + 1)))
https://stackoverflow.com/questions/68749250
复制