Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
667 views
in Technique[技术] by (71.8m points)

r - Delete rows based on multiple conditions with dplyr

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.

This is my code:

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'))

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')) 

Thanks a lot for your help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Adjusting your second question (not tested)

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') ))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...