gpt4 book ai didi

r - 通过 id R 查找时差

转载 作者:行者123 更新时间:2023-12-04 11:23:29 27 4
gpt4 key购买 nike

我有以下数据(df)

Id        Timestamp                 Event
1 2015-11-06 06:11:43 mail subscribed
1 2015-11-06 06:15:43 Invoice created
1 2015-11-06 09:15:43 phone call
2 2015-11-07 08:15:43 New subscription
2 2015-11-07 08:20:43 Added to customer list.

我正在寻找以下内容,(每个 id 的时差)

例如Id=1有3个不同时间的不同事件,我想根据Id计算事件之间各个时间的差异。
Id        Timestamp                 Event                   Time Difference(Mins)
1 2015-11-06 06:11:43 mail subscribed 0.0
1 2015-11-06 06:15:43 Invoice created 5.0
1 2015-11-06 09:15:43 phone call 180.0
2 2015-11-07 08:15:43 New subscription 0.0
2 2015-11-07 08:20:43 Added to customer list 5.0

我尝试了以下代码,
 diff = function(x) as.numeric(x - lag(x) )
or diff = function (x) as.numeric(0L,diff(x))
setDT(df)[, diff2 := diff(timestamp), by = Id]

但是这段代码输出不规则的结果。有什么帮助吗?

最佳答案

试试 ave .不使用任何包。

transform(df, Diff = ave(as.numeric(Timestamp), Id, FUN = function(x) c(0, diff(x))/60))

给予:
  Id           Timestamp                            Event Diff
1 1 2015-11-06 06:11:43 mail subscribed 0
2 1 2015-11-06 06:15:43 Invoice created 4
3 1 2015-11-06 09:15:43 phone call 180
4 2 2015-11-07 08:15:43 New subscription 0
5 2 2015-11-07 08:20:43 Added to customer list 5

注:这用于输入 data.frame, DF
Lines <- "Id,        Timestamp,                 Event
1, 2015-11-06 06:11:43, mail subscribed
1, 2015-11-06 06:15:43, Invoice created
1, 2015-11-06 09:15:43, phone call
2, 2015-11-07 08:15:43, New subscription
2, 2015-11-07 08:20:43, Added to customer list"

df <- read.csv(text = Lines)
df$Timestamp <- as.POSIXct(df$Timestamp)

更新 根据评论。

关于r - 通过 id R 查找时差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33960190/

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