使用dplyr根据多个条件删除行 [英] Delete rows based on multiple conditions with dplyr

查看:205
本文介绍了使用dplyr根据多个条件删除行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图根据多列中的值删除数据集中的特定行。仅当满足所有3列中的条件时,才应删除一行。

I am trying to delete specific rows in my dataset based on values in multiple columns. A row should be deleted only when a condition in all 3 columns is met.

这是我的代码:

test_dff %>%
  filter(contbr_nm != c('GAITHER, BARBARA', 'PANIC, RADIVOJE', 'KHAN, RAMYA') & 
           contbr_city != c('APO AE', 'PORSGRUNN', 'NEW YORK') &
           contbr_zip != c('9309', '3924', '2586'))

此代码应删除表中的12行。相反,它删除了其中的绝大多数。我怀疑,只要满足条件之一,它就会删除所有可能的行。

This code should remove 12 rows in my table. Instead it removes a vast majority of them. I am suspecting, that it removes all the possible rows, whenever one of the conditions is met.

有没有更好的解决方案,或者我必须使用这种方法,

Is there a better solution, or do I have to use the approach, described here?

我需要分别指定每个组合吗?这样吗这种方法还会删除太多行,因此也是错误的。

Do I need to specify each combination separately? Like so? This approach also deletes far too many rows, so it is also wrong.

test_dff %>%
  filter((contbr_nm != 'GAITHER, BARBARA' & contbr_city != 'APO AE' & contbr_zip != '9309') &
         (contbr_nm != 'PANIC, RADIVOJE' & contbr_city != 'PORSGRUNN' & contbr_zip != '3924') &
           (contbr_nm != 'KHAN, RAMYA' & contbr_city != 'NEW YORK' & contbr_zip != '2586') )

如果我只关注基于一个变量删除行,则这段代码有效:

If I focus on deleting rows only based on one variable, this piece of code works:

test_dff %>%
  filter(contbr_zip != c('9309')) %>%
  filter(contbr_zip != c('3924')) %>%
  filter(contbr_zip != c('2586'))

为什么这种方法行不通?

Why does such an approach not work?

test_dff %>%
  filter(contbr_zip != c('9309','3924','2586')) 

非常感谢您的帮助。

推荐答案

这是一种基于联接的方法-所有项目都必须完全匹配。

Here is a join-based approach - all items must be exact matches.

main <- read.csv(text = "
id,name,city,zip
1,mary,new york,10017
2,jonah,new york,10016
3,tamil,manhattan,10019
4,vijay,harlem,10028
")

excludes <- read.csv(text = "
name,city,zip
jonah,new york,10016
vijay,harlem,10028
")

library(dplyr)
anti_join(main, excludes)

#   id  name      city   zip
# 1  3 tamil manhattan 10019
# 2  1  mary  new york 10017

这篇关于使用dplyr根据多个条件删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆