我正在尝试将data $ TIME(格式:06:07:11 PM)转换为小时(在这种情况下为18),以便我可以计算每小时的查询(呼叫)次数以绘制直方图或条形图。
有人可以帮我吗?
data = read.csv('X.csv')
data$TIME <- format(strptime(data$TIME, "%H:%M:%S %p"), format="%H:%M:%S")
但是上面的代码返回了NA ...
答案 0 :(得分:2)
使用strptime
,然后选择hour
组件。请注意,在使用%p
时,小时必须用%I
而不是%H
来表示。
strptime("07/01/2019 06:07:11 PM", "%m/%d/%Y %I:%M:%S %p")$hour
## [1] 18
发布者在回答问题后更改了问题,因此修改后的问题的答案是:
strptime("06:07:11 PM", "%I:%M:%S %p")$hour
## [1] 18
答案 1 :(得分:1)
您可以使用lubridate
和dplyr
来解决此问题。您可以使用lubridate解析日期,然后使用hour()
函数提取小时。然后计算在指定小时内的观察次数。
library(lubridate)
library(dplyr)
# create sample date to parse
sample_date <- "07/01/2019 06:07:11 PM"
# parse date using lubridate
# stands for day-month-year hour-minute-sconds
parsed_date <- dmy_hms(sample_date)
# generate sample date times
sample_dates <- seq(from = parsed_date, to = parsed_date + days(10), length.out = 240)
tibble(dates = sample_dates) %>%
mutate(hour = hour(dates)) %>%
group_by(hour) %>%
summarise(n_hour = n())
#> # A tibble: 24 x 2
#> hour n_hour
#> <int> <int>
#> 1 0 10
#> 2 1 10
#> 3 2 10
#> 4 3 10
#> 5 4 10
#> 6 5 10
#> 7 6 10
#> 8 7 10
#> 9 8 10
#> 10 9 10
#> # … with 14 more rows
由reprex package(v0.2.1)于2019-07-17创建