我有一个事故数据(称为df)。每一次事故都有一个#与它相关,一个#代表每一个参与的人,以及事故的类型。看起来是这样的:
x y z
accident #1 person A accident type #1
accident #1 person A accident type #2
accident #2 person A accident type #1
accident #2 person B accident type #2
accident #2 person B accident type #3
accident #3 person C accident type #1在上述案件中,A人发生了两起事故。在第一次事故中,有两种类型的事故与A人有关。人B与人A有关,但只涉及一次事故,有两种事故类型。C人也只参与了一次事故。
我想收集,也就是只参与过一次事故的人的子集。不过,我想把他们所有的事故类型都包括进去。所以使用上面的例子,我想要这样:
x y z
accident #2 person #2 accident type #2
accident #2 person #2 accident type #3
accident #3 person #3 accident type #1我怎么才能在R里这么做呢?
发布于 2017-05-01 17:50:27
您可以使用dplyr包,使用group_by、filter和n_distinct来完成这一任务。
library(dplyr)
df %>%
group_by(y) %>%
filter(n_distinct(x) == 1) %>%
ungroup()发布于 2017-05-02 03:11:40
我们可以使用data.table
library(data.table)
setcolorder(setDT(df)[, .SD[uniqueN(x)==1] , y], names(df))[]
# x y z
#1: accident #2 person B accident type #2
#2: accident #2 person B accident type #3
#3: accident #3 person C accident type #1https://stackoverflow.com/questions/43723632
复制相似问题