在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.
相关产品推荐
相关产品推荐

