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

R语言中如何同时使用&与|进行列选择及区分大小写筛选

Hey there! Let's work through your two dplyr select() issues one by one—getting the combined logical conditions right, and making sure you only pick columns starting with uppercase "PP".

Fixing the Logical Conditions (A AND B) OR C

Your original code was having trouble because select() doesn't handle operators like | directly between selection helpers. To implement "(starts with 'A' AND doesn't end with 'z') OR starts with 'PP'", you can use where() to run a custom check against each column name.

Here's a clean, readable way to write this:

library(dplyr)

read_spss("data13.sav") %>%
  select(where(~ (startsWith(.x, "A") && !endsWith(.x, "z")) || startsWith(.x, "PP")))
  • where() passes each column name (as .x) to the function we define.
  • startsWith() and endsWith() are base R functions that let us check column name patterns directly.
  • The logic (A && B) || C translates exactly to your desired "(Condition A AND B) OR Condition C".

Making the "PP" Match Case-Sensitive

By default, dplyr's starts_with() uses ignore.case = TRUE, which is why it's catching both "PP" and "pp" columns. To fix this, you have two easy options:

Option 1: Use base R's startsWith() (already case-sensitive)

The code above already uses base R's startsWith(), which is case-sensitive by default—so it will only match columns starting with uppercase "PP". Perfect!

Option 2: Use dplyr's starts_with() with ignore.case = FALSE

If you prefer sticking to dplyr's selection helpers, just add the ignore.case argument:

read_spss("data13.sav") %>%
  select(where(~ (starts_with(.x, "A", ignore.case = FALSE) && !ends_with(.x, "z", ignore.case = FALSE)) || starts_with(.x, "PP", ignore.case = FALSE)))

Quick Alternative with Regular Expressions

If you're comfortable with regex, you can also use matches() to combine all conditions in one pattern (case-sensitive by default):

read_spss("data13.sav") %>%
  select(matches("^A.*(?<!z)$|^PP", perl = TRUE))
  • ^A.*(?<!z)$: Matches columns starting with "A" and not ending with "z"
  • ^PP: Matches columns starting with "PP"
  • The | acts as an OR between the two patterns

内容的提问来源于stack exchange,提问作者grnpwdr

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:23:42