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

在R中如何筛选仅包含Apple的DataFrame行?

如何在R中筛选仅包含Apple的DataFrame行?

问题场景

现有如下R DataFrame:

Fruits
Apple:1
Apple:4
Bananna    
Papaya    
Orange, Apple:2

需要筛选出仅包含Apple相关内容的行,预期结果为:

Apple:1
Apple:4 

尝试使用dplyr::filter结合grepl('Apple', Fruits)筛选时,结果会包含Orange, Apple:2这行,不符合预期。


解决方案

要精确匹配整行仅为Apple:数字的内容,需要使用锚定整个字符串的正则表达式,结合grepl实现精准筛选:

library(dplyr)
# 筛选整行以Apple:开头、数字结尾的行
df <- df %>%
  filter(grepl('^Apple:\\d+$', Fruits))

正则说明

  • ^:匹配字符串的起始位置,确保行开头就是Apple:
  • Apple::匹配固定文本"Apple:"
  • \\d+:匹配一个或多个数字(适配数据里的1、4这类数字后缀)
  • $:匹配字符串的结束位置,确保行末尾没有其他多余内容

如果需要兼容**纯Apple(不带:数字)**的行,可以把正则调整为:

grepl('^Apple(:\\d+)?$', Fruits)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 09:57:12