如果第一行满足特定条件,则删除所有匹配 ID 的数据

标签 r data.table

我正在尝试删除 client_id 的所有数据,当该客户的 first 项目的 score 匹配时(按日期排序时)一个特定的条件。根据我的阅读,data.table 似乎可以做到这一点,而且我已经能够几乎到达那里。

这是一些示例数据:

client_id <- c(1,1,1,2,2,3,3,3,3,4,4)
date <- c("1/1/2021", "1/2/2021", "1/3/2021", "5/1/2021", "10/1/2021", "10/1/2021", "11/1/2021", "1/2/2021", "10/9/2021", "15/9/2021", "16/10/2021")
date <- as.Date(date, '%d/%m/%Y')
score <- c(15,10,19,20,10,25,20,15,10,30,5)
df <- data.frame(client_id, date, score)

我试过这个:

df <-setDT(df)
df[client_id %in% df[score > 16, client_id], ]

我希望这会删除 client_id 1,因为 first 分数 < 16。但是,这似乎只在所有分数都 > 16 时才将它们全部删除。

最佳答案

您可以将 .SDfirst 一起使用,前提是 df 中的日期按升序排列:

df[,.SD[first(score)>16],by=client_id]
   client_id       date score
       <num>     <Date> <num>
1:         2 2021-01-05    20
2:         2 2021-01-10    10
3:         3 2021-01-10    25
4:         3 2021-01-11    20
5:         3 2021-02-01    15
6:         3 2021-09-10    10
7:         4 2021-09-15    30
8:         4 2021-10-16     5

关于如果第一行满足特定条件,则删除所有匹配 ID 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70982065/

相关文章:

html - 从 R : option values in specific select elements 中的 HTML 页面中提取数据

r - data.table 性能在按组计算列的滞后差异时不会线性扩展

r - 在 data.table 中插入一行

在 data.table 中的两列上滚动一个函数

r - 下载 {data.table} 包时遇到问题

r - 数据框 - 在 R 中添加具有条件的出现次数

R:Plotly:树形图:仅对最低标签着色

r - 向 ggalt::geom_dumbbell 图添加图例并对 y 轴进行排序

r - 将决策边界拟合到 R 中的逻辑回归模型

r - 向数据表添加列