gpt4 book ai didi

r - 日期差异直方图 - 分组

转载 作者:行者123 更新时间:2023-12-04 06:14:43 25 4
gpt4 key购买 nike

前几天我问了一个关于如何获得日期差异直方图的问题。我想做同样的事情,但对于组和箱线图,使用格子的 bwplot。本质上,对于我拥有的 5 个不同来源中的每一个,都需要 1 个带有 5 个方框图的图像(我在下面的示例中显示了 2 个)——类似这样的 image .

我花了很长时间试图弄清楚这一点,但无法得到它。

我能想到的最接近的

df <- read.csv("~/dates.csv", header = TRUE, sep = ",", quote = "\"")
a <- aggregate(as.POSIXct(as.character(df$REQUEST_DATE), format="%m/%d/%Y %H:%M:%S"), list(SOURCE=df$SOURCE), diff) # not sure if this is right (and I need -diff, but can't do that)
# now what? I seem to know how to access a$SOURCE, but don't know how to look at the data associated with a$SOURCE.

数据(~/dates.csv):
"SOURCE","REQUEST_DATE"
"A","09/11/2011 09:28:48"
"A","09/11/2011 09:21:15"
"A","09/11/2011 09:15:42"
"A","09/11/2011 09:12:18"
"D","09/13/2011 09:06:53"
"D","09/13/2011 09:06:18"
"D","09/13/2011 08:56:55"
"D","09/13/2011 08:56:18"
"D","09/13/2011 08:55:43"
"D","09/13/2011 08:39:07"

最佳答案

这是使用 plyr 的解决方案数据分析包,以及 ggplot2情节包:

读取数据。注意使用 stringsAsFactors=FALSE - 这样可以省去很多转换为 as.character 的麻烦之后:

df <- read.csv(textConnection('
"SOURCE","REQUEST_DATE"
"A","09/11/2011 09:28:48"
"A","09/11/2011 09:21:15"
"A","09/11/2011 09:15:42"
"A","09/11/2011 09:12:18"
"D","09/13/2011 09:06:53"
"D","09/13/2011 09:06:18"
"D","09/13/2011 08:56:55"
"D","09/13/2011 08:56:18"
"D","09/13/2011 08:55:43"
"D","09/13/2011 08:39:07"
'), stringsAsFactors=FALSE)

转换为 POSIX 日期格式:
df$REQUEST_DATE <- as.POSIXct(df$REQUEST_DATE, format="%m/%d/%Y %H:%M:%S")

负载 plyr并使用 ddply a) 按 SOURCE 分组,b) 计算 difftime,c) 将结果分组到一个 data.frame 中,只需一步:
library(plyr)
df_diff <- ddply(df, .(SOURCE), summarize, TIME_DIFF=-unclass(diff(REQUEST_DATE)))
df_diff
SOURCE TIME_DIFF
1 A 7.55
2 A 5.55
3 A 3.40
4 D 35.00
5 D 563.00
6 D 37.00
7 D 35.00
8 D 996.00

负载 ggplot2和情节。该图看起来有点垃圾 - 那是因为样本数据集很小。它将在更大的数据集上更好地工作,即您将在中值、范围和异常值之间得到清晰的分离。
library(ggplot2)
ggplot(df_diff, aes(y=TIME_DIFF, x=SOURCE)) + geom_boxplot()

enter image description here

关于r - 日期差异直方图 - 分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7403296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com