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

如何用dplyr按向量中首字母筛选dataframe/tibble列?

筛选列名以向量中任意元素开头的列

要实现这个需求,基于dplyr包有两种简洁实用的方法:

方法1:用matches()结合正则表达式

把目标前缀向量转换成匹配字符串开头的正则表达式,传给matches()即可完成筛选:

library(dplyr)

columns_to_select <- c("A", "B", "C")
# 构建正则规则:^表示匹配列名开头,|表示逻辑或
prefix_pattern <- paste0("^(", paste(columns_to_select, collapse = "|"), ")")

# 执行筛选
df %>% select(matches(prefix_pattern))

方法2:用startsWith()直接判断

利用startsWith()支持多前缀向量的特性,直接生成列的逻辑筛选条件:

df %>% select(startsWith(colnames(df), columns_to_select))

测试示例

用实际数据验证效果:

# 构造测试数据集
df <- tibble(
  A1 = 1:3,
  B2 = 4:6,
  Cxy = 7:9,
  D3 = 10:12,
  AE = 13:15
)

columns_to_select <- c("A", "B", "C")

# 筛选后会得到A1、B2、Cxy、AE这几列
df %>% select(startsWith(colnames(df), columns_to_select))

内容的提问来源于stack exchange,提问作者D. Studer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 08:45:27