gpt4 book ai didi

r - 过滤组内给定行元素下方的行

转载 作者:行者123 更新时间:2023-12-04 23:21:00 24 4
gpt4 key购买 nike

我有一个数据框,每行中有一组日期事件,链接到一个位置。在每个位置中,我都有一个索引事件和一系列可能在索引事件之前和/或之后发生的各种匹配事件。我需要对每个位置的索引事件之前发生的所有匹配事件进行子集化。数据结构看起来像这样。

locid    match      date          score      iid
1 index 4/11/2013 15 1
1 matched 1/09/2013 23 2
1 matched 14/04/2013 1 3
1 matched 7/1/2014 21 4
2 index 2/4/2013 12 1
2 matched 1/2/2013 10 2
3 index 1/5/2013 23 1
3 matched 2/5/2013 10 2
4 index 3/3/2013 9 1
4 matched 10/2/2013 32 2
4 matched 1/10/2012 15 3
4 matched 4/3/2013 12 4
4 matched 10/3/2013 10 5

而且我需要对数据框进行子集化,以便我最终只得到日期低于每个位置的索引事件日期的行:
locid    match      date          score      iid
1 matched 1/09/2013 23 2
1 matched 14/04/2013 1 3
2 matched 1/2/2013 10 2
4 matched 10/2/2013 32 2
4 matched 1/10/2012 15 3

我第一次在这里问,所以我希望我没有以错误的方式做这件事。我在 R 中尝试了各种不同的解决方案,但我正在努力寻找合适的解决方案。

最佳答案

这是一个 data.table可能性(假设您的数据名为 df )

library(data.table)
setDT(df)[, date := as.Date(date, format = "%d/%m/%Y")][,
.SD[date < date[match == "index"]], by = locid]
# locid match date score iid
# 1: 1 matched 2013-09-01 23 2
# 2: 1 matched 2013-04-14 1 3
# 3: 2 matched 2013-02-01 10 2
# 4: 4 matched 2013-02-10 32 2
# 5: 4 matched 2012-10-01 15 3

可能的基础 R 解决方案
df <- transform(df, date = as.Date(date, format = "%d/%m/%Y"))
do.call(rbind, by(df, df$locid, FUN = function(x) x[with(x, date < date[match == "index"]), ]))
# locid match date score iid
# 1.2 1 matched 2013-09-01 23 2
# 1.3 1 matched 2013-04-14 1 3
# 2 2 matched 2013-02-01 10 2
# 4.10 4 matched 2013-02-10 32 2
# 4.11 4 matched 2012-10-01 15 3

另一个可能的基础 R 解决方案
df <- transform(df, date = as.Date(date, format = "%d/%m/%Y"))
do.call(rbind, lapply(split(df, df$locid), function(x) x[with(x, date < date[match == "index"]), ]))
# locid match date score iid
# 1.2 1 matched 2013-09-01 23 2
# 1.3 1 matched 2013-04-14 1 3
# 2 2 matched 2013-02-01 10 2
# 4.10 4 matched 2013-02-10 32 2
# 4.11 4 matched 2012-10-01 15 3

这里的基本思想是转换您的 date列到 Date类,所以 R 将能够识别它的顺序。之后,我们基本上用 locid来分割数据并对每个块应用过滤函数,该函数仅选择 date 之前的日期。哪里 match == index

关于r - 过滤组内给定行元素下方的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26733917/

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