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

R语言:筛选classification_id以8开头的数据时管道运算符报错及匹配问题求助

问题解决建议

1. 先修复管道运算符%>%的报错

%>%是dplyr包提供的管道运算符,运行代码前必须先加载dplyr(或包含它的tidyverse全家桶):

library(dplyr)
# 也可以直接加载整个tidyverse:library(tidyverse)

2. 修正"筛选以8开头的classification_id"的逻辑

你之前用的8*写法错误,原因如下:

  • 直接用== 8*是无效语法:==是精确匹配,R会把*当成乘法运算符,完全无法实现模糊匹配;
  • 正则表达式里8*的含义是"匹配0个或多个8",不是"以8开头",正确的正则应该用^8(^表示字符串的起始位置)。

正确写法一(正则匹配,兼容字符/数值型ID)

sales_pharmacy %>%
  filter(grepl(pattern = "^8", x = as.character(classification_id))) %>%
  select(classification_id, classification_name)

如果classification_id本身就是字符型,可以省略as.character()转换。

正确写法二(提取首位字符判断,直观易懂)

sales_pharmacy %>%
  filter(substr(as.character(classification_id), 1, 1) == "8") %>%
  select(classification_id, classification_name)

3. 可视化子分类的补充示例

筛选出目标数据后,用ggplot2(属于tidyverse)做可视化,比如展示子分类的分布:

library(ggplot2)

sales_pharmacy %>%
  filter(grepl("^8", as.character(classification_id))) %>%
  ggplot(aes(x = classification_name)) +
  geom_bar(fill = "#2E86AB") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 22:40:42