簡體   English   中英

如何計算條件在 R 中以分鍾為單位找到兩個 DateTime 之間的差異

[英]How to calculate condition find the difference between two DateTime in minute in R

我模擬數據,DateTime 是數據庫中的日期類型。 我想計算兩個 DateTime 之間的分鍾差,從組中找到 integer 或小數的平均時間。
它僅通過確認進行計算。

可能類似於此 output 數據幀。

這是我的期望圖。 橙色是拒絕 grom group1

在此處輸入圖像描述

我該怎么做? 謝謝你的到來。

您還可以使用dplyrggplot2包來完成此操作:此外,如果您的日期是字符串,您可以使用lubridate package。

要獲得差異和平均值:

library(dplyr)
#load if you need to convert strings to dates
library(lubridate)

#df as in example, check 'Data' below
df_new <- df %>%
#counting differences in minutes
  mutate(difference = difftime(ymd_hms(date1), ymd_hms(date2), unit = "mins")) %>%
#grouping dates by 'abc' group
  group_by(group1) %>%
#counting average difference for every 'abc' group in minutes
  mutate(average = mean(difference))

制作 plot:

library(ggplot2)

#passing summarized data to ggplot to create a plot and choosing aesthetics / dimensions to be ploted
ggplot(df_new, aes(y = avg_diff, x = group1, fill = group2)) +
#choosing type of plot
  geom_col() +
#flipping x and y axis
  coord_flip() +
#choosing colors
  scale_fill_manual(values = c("green", "orange"))

結果圖

數據:

df <- data.frame(date1 = c("2020-04-05 11:51:51",
                           "2020-04-06 13:55:16",
                           "2020-04-06 14:26:56",
                           "2020-04-06 14:35:05",
                           "2020-04-06 14:36:00",
                           "2020-04-06 14:36:31",
                           "2020-04-06 14:36:31",
                           "2020-04-04 19:00:38",
                           "2020-04-05 21:22:23"),
                 date2 = c("2020-04-05 10:10:23",
                           "2020-04-06 11:41:20",
                           "2020-04-06 14:25:58",
                           "2020-04-06 14:26:03",
                           "2020-04-06 14:32:02",
                           "2020-04-06 14:33:35",
                           "2020-04-06 14:33:35",
                           "2020-04-04 18:30:29",
                           "2020-04-05 21:21:46"),
                 group1 = c("a", "b", "a", "a", "a", "b", "b", "c", "c"),
                 group2 = c("accept", "accept", "accept", "denny", "denny", "accept", "accept", "denny", "denny"),
                 stringsAsFactors = F)

暫無
暫無

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

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