簡體   English   中英

在 R 中使用 cut() 函數將日期轉換為 15 分鍾間隔的不可預測的結果

[英]Unpredictable results using cut() function in R to convert dates to 15 minute intervals

好吧,這讓我發瘋。

我有幾個數據集的時間值需要匯總到 15 分鍾的時間間隔。

我在這里找到了一個可以在一個數據集上完美運行的解決方案。 但是在下一個我嘗試做的事情上,我得到了奇怪的結果。 我有一列字符數據表示日期:

                 BeginTime
-------------------------------
    1           1/3/19 1:50 PM
    2           1/3/19 1:30 PM
    3           1/3/19 4:56 PM
    4          1/4/19 11:23 AM
    5           1/6/19 7:45 PM
    6          1/7/19 10:15 PM
    7          1/8/19 12:02 PM
    8          1/9/19 10:43 PM

我正在使用以下代碼(這正是我在其他數據集上使用的,除了名稱)

df$by15 = cut(mdy_hm(df$BeginTime), breaks="15 min")

但我得到的是:

                    BeginTime              by15
-------------------------------------------------------
    1           1/3/19 1:50 PM      2019-01-03 13:36:00
    2           1/3/19 1:30 PM      2019-01-03 13:21:00
    3           1/3/19 4:56 PM      2019-01-03 16:51:00
    4          1/4/19 11:23 AM      2019-01-04 11:21:00
    5           1/6/19 7:45 PM      2019-01-06 19:36:00
    6          1/7/19 10:15 PM      2019-01-07 22:06:00
    7          1/8/19 12:02 PM      2019-01-08 11:51:00
    8          1/9/19 10:43 PM      2019-01-09 22:36:00
    9         1/10/19 11:25 AM      2019-01-10 11:21:00

關於為什么我得到這樣的隨機時間而不是我正在尋找的 15 分鍾間隔的任何建議? 就像我說的,這在其他數據集上運行良好。

您可以使用 lubridate::round_date() 函數,它將按如下方式匯總您的日期時間數據;

library(lubridate) # To handle datetime data
library(dplyr) # For data manipulation

# Creating dataframe
df <-
  data.frame(
    BeginTime = c("1/3/19 1:50 PM", "1/3/19 1:30 PM", "1/3/19 4:56 PM",
                  "1/4/19 11:23 AM", "1/6/19 7:45 PM", "1/7/19 10:15 PM",
                  "1/8/19 12:02 PM", "1/9/19 10:43 PM")
  )

df %>%
  # First we parse the data in order to convert it from string format to datetime
  mutate(by15 = parse_date_time(BeginTime, '%d/%m/%y %I:%M %p'),
         # We roll up the data/round it to 15 minutes interval
         by15 = round_date(by15, "15 mins"))
# 
# BeginTime                by15
# 1/3/19 1:50 PM   2019-03-01 13:45:00
# 1/3/19 1:30 PM   2019-03-01 13:30:00
# 1/3/19 4:56 PM   2019-03-01 17:00:00
# 1/4/19 11:23 AM  2019-04-01 11:30:00
# 1/6/19 7:45 PM   2019-06-01 19:45:00
# 1/7/19 10:15 PM  2019-07-01 22:15:00
# 1/8/19 12:02 PM  2019-08-01 12:00:00
# 1/9/19 10:43 PM  2019-09-01 22:45:00

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM