You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中选取与「状态非'Open'且类型为BMW/VW/Benz」相反的DataFrame行?

How to Reverse This R DataFrame Filter

Got it, let's break this down step by step! First, let's recap your original filter logic: you're selecting rows where:

  • status is not equal to 'Open', AND
  • type is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:11:39