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

在R语言中筛选数据框:保留开头含四位数字的条目

筛选三级编号条目解决方案

Base R 实现

直接用grepl结合正则表达式匹配三级编号格式的条目:

filtered_df <- df[grepl("^(\\d+\\.){2}\\d+ ", df$items), ]
print(filtered_df)

正则表达式^(\\d+\\.){2}\\d+ 的作用:

  • ^ 锚定字符串开头
  • (\\d+\\.){2} 匹配两组「数字+小数点」(对应三级编号的前两段,如01.)
  • \\d+ 匹配第三段数字及后续空格,确保和食品名称区分开

Tidyverse 风格实现

如果用stringr包,代码更直观:

library(stringr)
library(dplyr)

filtered_df <- df %>% 
  filter(str_detect(items, "^(\\d+\\.){2}\\d+ "))

filtered_df

两种方法都会得到目标结果:

items
3 01.1.1 Food Item 3
4 01.1.2 Food Item 4
5 01.1.3 Food Item 5
8 02.1.1 Food Item 8
11 10.1.1 Food Item 11
12 10.1.2 Food Item 12

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 03:15:57