问题描述
我有一个纵向数据集,如果他们在任何时间点都不满足 id
指示的标准,我想在其中删除个人 (criteria == 1
)。把它放在上下文中,我们可以说 criteria
表示个人在此期间的任何时间是否生活在感兴趣的区域。
使用一些与我的结构相似的玩具数据:
id <- c(1,1,2,3,4,5,5)
time <- c(1,3)
event <- c(0,1)
criteria <- c(1,1)
df <- data.frame(cbind(id,time,event,criteria))
> df
id time event criteria
1 1 1 0 1
2 1 2 1 0
3 1 3 0 0
4 2 1 1 0
5 2 2 0 0
6 2 3 0 0
7 3 1 0 0
8 3 2 0 0
9 3 3 0 0
10 4 1 0 1
11 4 2 1 1
12 4 3 0 1
13 5 1 1 0
14 5 2 0 0
15 5 3 1 1
因此,通过删除在所有时间点 (id
) 中具有 criteria == 0
的任何 time
将导致最终结果如下所示:
id time event criteria
1 1 1 0 1
2 1 2 1 0
3 1 3 0 0
4 4 1 0 1
5 4 2 1 1
6 4 3 0 1
7 5 1 1 0
8 5 2 0 0
9 5 3 1 1
我一直试图通过使用 dplyr::group_by(id)
来实现这一点,然后根据标准进行过滤,但这并没有达到我想要的结果。我更喜欢 tidyverse
解决方案! :D
谢谢!
解决方法
df %>%
group_by(id) %>%
# looking for the opposite (i.e. !) of criteria == 1 at least 1 time
mutate(is_good = !any(criteria == 1)) %>%
filter(is_good)
,
如果您愿意查看我推荐的 data.table,就这么简单:
<p id="ctl13_ctl00_PgLnks" style="color: #0066ff;" align="center">
۶۷۳ رکورد پیدا شد | در زمان ۳۵ میلی ثانیه | نمایش در ۱۲ صفحه
<br>
<a href="/Admin.aspx?mod=Reports&Knd=PersReport&do=Se&FID=2&Page=1">
<img src="Images/Icons/PgPrev.gif" border="0" title="صفحه قبل" align="absmiddle">
</a>
<a href="/Admin.aspx?mod=Reports&Knd=PersReport&do=Se&FID=2&Page=1" style="background-color:#ffffef;padding:3px;border:#a0a0a0 solid 1px;"> ۱ </a>
<a href="/Admin.aspx?mod=Reports&Knd=PersReport&do=Se&FID=2&Page=3"><img src="Images/Icons/PgNext.gif" border="0" title="صفحه بعد" align="absmiddle"></a></p>
有关
library(data.table)
setDT(df) # make it a data.table
df[,.SD[ !all(criteria==0) ],by=id ]
习语的一般介绍和解释,请参阅此页面:
https://cran.r-project.org/web/packages/data.table/vignettes/datatable-intro.html