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

如何在R语言中使用dplyr筛选不以A或J开头的行?

使用dplyr筛选name列不以A/J开头的行

原始数据

df <- data.frame(name = c("James", "jonathan", "Abel", "Cynthia", "Cornelius", "alex"))

简洁dplyr解决方案

结合dplyr和stringr包(后者属于tidyverse生态,常与dplyr搭配使用):

library(dplyr)
library(stringr)

df_filtered <- df %>%
  filter(!str_detect(name, "^[aj]", ignore.case = TRUE))

代码说明

  • str_detect(name, "^[aj]", ignore.case = TRUE):通过正则表达式^[aj]匹配以A/a或J/j开头的字符串,ignore.case = TRUE忽略大小写差异,覆盖数据里的大小写混合情况
  • !:对匹配结果取反,筛选出不以A/a或J/j开头的行

筛选结果

df_filtered
#>       name
#>    Cynthia
#>  Cornelius

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 19:12:07