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()andendsWith()are base R functions that let us check column name patterns directly.- The logic
(A && B) || Ctranslates 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

