将时间的特征向量转换为适当的格式并在 R 中进行分类
Convert character vector of times into proper format and bin in R
所以我有一个向量,如下所示:
TIME
7:16:00
16:00:00
17:35:00
16:10:00
5:25:00
18:00:00
这些被作为字符串读入R。我的目标是将它们分成 4 组
群组
- 容器 1:12:01am - 6:00am
- 容器 2:6:01am - 12:00pm
- 容器 3:12:01pm - 6:00pm
- 容器 4:6:01pm - 12:00am
我该怎么做呢?首选是使用 lubridate
最终输出:
TIME Bin
7:16:00 Bin 2: 6:01am - 12:00pm
16:00:00 Bin 3: 12:01pm - 6:00pm
17:35:00 Bin 3: 12:01pm - 6:00pm
16:10:00 Bin 3: 12:01pm - 6:00pm
5:25:00 Bin 1: 12:01am - 6:00am
18:00:00 Bin 3: 12:01pm - 6:00pm
这是一种使用 lubridate
和 tidyverse
的可能性
library(lubridate)
library(tidyverse)
df <- data.frame(TIME =
c("7:16:00", "16:00:00",
"17:35:00", "16:10:00",
"5:25:00", "18:00:00")
)
df %>%
mutate(Bin = paste("Bin ", ceiling((hour(hms(TIME) + minute(hms(TIME)) / 60) / 6)))
TIME Bin
1 7:16:00 Bin 2
2 16:00:00 Bin 3
3 17:35:00 Bin 3
4 16:10:00 Bin 3
5 5:25:00 Bin 1
6 18:00:00 Bin 3
这是一个基本的 R 替代方案:
df$h <- as.numeric(sub("(\d+):.*", "\1", df$TIME))
df$m <- as.numeric(sub(".*:(\d+):.*", "\1", df$TIME))
df$Bin <- paste("Bin", ceiling((df$h + df$m / 60) / 6))
所以我有一个向量,如下所示:
TIME
7:16:00
16:00:00
17:35:00
16:10:00
5:25:00
18:00:00
这些被作为字符串读入R。我的目标是将它们分成 4 组
群组
- 容器 1:12:01am - 6:00am
- 容器 2:6:01am - 12:00pm
- 容器 3:12:01pm - 6:00pm
- 容器 4:6:01pm - 12:00am
我该怎么做呢?首选是使用 lubridate
最终输出:
TIME Bin
7:16:00 Bin 2: 6:01am - 12:00pm
16:00:00 Bin 3: 12:01pm - 6:00pm
17:35:00 Bin 3: 12:01pm - 6:00pm
16:10:00 Bin 3: 12:01pm - 6:00pm
5:25:00 Bin 1: 12:01am - 6:00am
18:00:00 Bin 3: 12:01pm - 6:00pm
这是一种使用 lubridate
和 tidyverse
library(lubridate)
library(tidyverse)
df <- data.frame(TIME =
c("7:16:00", "16:00:00",
"17:35:00", "16:10:00",
"5:25:00", "18:00:00")
)
df %>%
mutate(Bin = paste("Bin ", ceiling((hour(hms(TIME) + minute(hms(TIME)) / 60) / 6)))
TIME Bin
1 7:16:00 Bin 2
2 16:00:00 Bin 3
3 17:35:00 Bin 3
4 16:10:00 Bin 3
5 5:25:00 Bin 1
6 18:00:00 Bin 3
这是一个基本的 R 替代方案:
df$h <- as.numeric(sub("(\d+):.*", "\1", df$TIME))
df$m <- as.numeric(sub(".*:(\d+):.*", "\1", df$TIME))
df$Bin <- paste("Bin", ceiling((df$h + df$m / 60) / 6))