如何在R中选取与「状态非'Open'且类型为BMW/VW/Benz」相反的DataFrame行?
Got it, let's break this down step by step! First, let's recap your original filter logic: you're selecting rows where:
statusis not equal to 'Open', ANDtypeis one of 'BMW', 'VW', or 'Benz'
To reverse this (i.e., select all rows that don't match the above combined condition), you have two straightforward approaches—either negate the entire original condition directly, or use De Morgan's laws to rewrite the reverse logic more explicitly.
Approach 1: Negate the Entire Original Condition
You can wrap your original filter logic in a ! (not) operator to flip the selection.
Base R Example
If your DataFrame is named df:
# Original filter logic stored for clarity original_condition <- (df$status != 'Open') & (df$type %in% c('BMW', 'VW', 'Benz')) # Reverse filter: select rows where original condition is FALSE reverse_df <- df[!original_condition, ]
Or condensed into one line:
reverse_df <- df[!((df$status != 'Open') & (df$type %in% c('BMW', 'VW', 'Benz'))), ]
dplyr Example
If you prefer tidyverse syntax:
library(dplyr) reverse_df <- df %>% filter(!((status != 'Open') & (type %in% c('BMW', 'VW', 'Benz'))))
Approach 2: Rewrite with De Morgan's Laws
De Morgan's laws tell us that !(A & B) is equivalent to !A | !B. Applying that to your original condition:
!A=status == 'Open'(opposite of "status isn't Open")!B=!(type %in% c('BMW', 'VW', 'Benz'))(opposite of "type is in the brand list")
So the reverse condition becomes: status is 'Open' OR type is NOT in the brand list (or both). This version is often more readable at a glance.
Base R Example
reverse_df <- df[(df$status == 'Open') | !(df$type %in% c('BMW', 'VW', 'Benz')), ]
dplyr Example
library(dplyr) reverse_df <- df %>% filter(status == 'Open' | !(type %in% c('BMW', 'VW', 'Benz')))
Both approaches produce identical results—pick whichever feels more intuitive for your code context!
内容的提问来源于stack exchange,提问作者user5879741

