根据多个条件删除行

根据多个条件删除行

本文介绍了使用 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 根据多个条件删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 21:01