我正在处理一个事务数据集,它以hhmmss格式报告事务时间。例如,204629,215450等
我想从给定的列中推导出一个因子变量,其水平表示一天中的某些小时,例如12-3点、3-6点等。
我可以考虑使用str_sub函数从给定变量中选择小时值,并将它们转换为因子。但是,是否有更有效的方法来实现这一点呢?
发布于 2020-04-02 20:19:10
您可以使用dplyr::mutate
和stringr::str_sub
创建hour
列,然后使用cut
将hour
列划分为您的句点。
library(dplyr)
library(stringr)
library(lubridate)
tibble(string = c("215450", "220102", "020129")) %>%
mutate(hour = str_sub(string, 1, 2) %>% as.numeric,
minute = str_sub(string, 3, 4) %>% as.numeric,
second = str_sub(string, 5, 6) %>% as.numeric,
time = str_c(hour, minute, second, sep = ":") %>% hms()) %>%
mutate(period = cut(hour, breaks = 2, labels = c("period one", "period two")))
# A tibble: 3 x 6
string hour minute second time period
<chr> <dbl> <dbl> <dbl> <Period> <fct>
1 215450 21 54 50 21H 54M 50S period two
2 220102 22 1 2 22H 1M 2S period two
3 020129 2 1 29 2H 1M 29S period one
https://stackoverflow.com/questions/61000082
复制相似问题