R语言中如何移除匹配多个模式的多行数据?解决grepl仅识别首个模式的问题
Hey there! The issue you're seeing is because grepl() doesn't accept a vector of patterns directly—when you pass more than one, it only uses the first one (which is exactly what the warning is telling you). Here's how to fix this:
The Quick Fix for Base R
Combine all your patterns into a single string separated by | (which means "OR" in regex). You can do this using paste() with collapse = "|":
# Define your patterns once for clarity phylum_patterns <- c("Chloroflexota", "Desulfobacterota_D", "Gemmatimonadota") # Combine into one regex pattern that matches any of the entries combined_pattern <- paste(phylum_patterns, collapse = "|") # Filter the data frame to exclude rows matching any of the patterns custom_BGCs_filtered <- custom_BGCs[!grepl(combined_pattern, custom_BGCs$Phylum), ]
If you prefer a concise one-liner:
custom_BGCs_filtered <- custom_BGCs[!grepl(paste(c("Chloroflexota","Desulfobacterota_D", "Gemmatimonadota"), collapse = "|"), custom_BGCs$Phylum), ]
Bonus: Tidyverse Approach (dplyr + stringr)
If you use the tidyverse ecosystem, filter() paired with str_detect() makes this even more readable:
library(dplyr) library(stringr) custom_BGCs_filtered <- custom_BGCs %>% filter(!str_detect(Phylum, paste(phylum_patterns, collapse = "|")))
If you want to treat your phylum names as literal strings (no regex interpretation, just in case they contain special characters), add fixed = TRUE:
# Base R version with literal matching custom_BGCs_filtered <- custom_BGCs[!grepl(combined_pattern, custom_BGCs$Phylum, fixed = TRUE), ] # Tidyverse version with literal matching custom_BGCs_filtered <- custom_BGCs %>% filter(!str_detect(Phylum, fixed(phylum_patterns)))
Why This Works
By combining patterns with |, you're telling the function to look for any of the specified phyla in the Phylum column. The ! operator inverts the match, so we keep only the rows that don't match any of your target patterns.
内容的提问来源于stack exchange,提问作者Valentin

