繁体   English   中英

根据条件语句从数据框中删除行?

[英]Removing rows from a dataframe based on a conditional statement?

我有一个意外的数据框(称为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中做到这一点?

您可以使用dplyr软件包 ,使用group_byfiltern_distinct来做到这n_distinct

library(dplyr)
df %>%
  group_by(y) %>%
  filter(n_distinct(x) == 1) %>%
  ungroup()

我们可以使用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 #1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM