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

在R中筛选mpg数据集trans列以‘auto’开头的行

在R中筛选mpg数据集trans列以"auto"开头的行

针对需求,这里提供两种常用的实现方式:

方法一:基础R实现

利用grepl()函数结合正则表达式匹配字符串开头:

# 加载内置的mpg数据集
data(mpg)
# 筛选trans列以"auto"开头的行
auto_rows <- mpg[grepl("^auto", mpg$trans), ]
# 查看筛选后的trans列结果
auto_rows$trans

其中^auto是正则表达式规则,^表示匹配字符串的起始位置,确保只筛选以"auto"开头的记录,不受括号内内容影响。

方法二:dplyr(tidyverse)实现

如果你习惯使用tidyverse风格的管道操作,可以用dplyr的filter()配合str_detect():

# 安装并加载dplyr(首次使用需安装)
# install.packages("dplyr")
library(dplyr)
data(mpg)

auto_rows <- mpg %>%
  filter(str_detect(trans, "^auto"))

# 查看结果
auto_rows$trans

两种方法最终都会得到你期望的输出:"auto(l5)" "auto(av)" "auto(l5)" "auto(av)" "auto(l5)" "auto(s6)" "auto(l5)" "auto(s6)" "auto(l5)"

内容的提问来源于stack exchange,提问作者Jennifer B.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 05:45:21