Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 基于条件语句从数据帧中删除行?_R - Fatal编程技术网

R 基于条件语句从数据帧中删除行?

R 基于条件语句从数据帧中删除行?,r,R,我有一个事故数据帧(称之为df)。每起事故都有一个与之相关的“a”,每个相关人员都有一个“a”,以及事故的类型。它看起来像这样: 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 per

我有一个事故数据帧(称之为
df
)。每起事故都有一个与之相关的“a”,每个相关人员都有一个“a”,以及事故的类型。它看起来像这样:

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中执行此操作?

您可以使用,使用
groupby
filter
n\u 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

缩进四个空格以生成代码块,或高亮显示并按CTRL+K键。请使用谷歌搜索此项,因为这是一种非常常见的操作operation@MichaelChirico我是R的新手,不确定谷歌到底要做什么。我发现的任何东西都不符合我的具体情况。然后详细说明你的发现,以及为什么它不适用——证明努力是很有帮助的