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

如何按字符串向量元素的首词筛选Data Frame?

按向量元素首词筛选数据集(非精确匹配)

需求

需要从数据框中筛选出col_1包含指定向量元素首词的条目,无需精确匹配:

  • 若向量元素是单个词(如"Orange"),直接匹配该词
  • 若向量元素是多词(如"Lemon ltd"),仅匹配其第一个单词(即"Lemon")

示例数据

# 构建示例数据框
Data <- data.frame(
  col_1 = c("Orange juice", "Orange cake", "Lemon curd", "Lemon pie", "Strawberry", "Lime tree"), 
  col_2 = c("food", "food", "food", "food", "fruit", "tree")
)

# 用于筛选的目标向量(取自另一数据集)
target_vector <- c("Orange", "Lemon ltd", "Grapefruit", "Peach juice") 

解决步骤

  1. 提取向量元素的首词:使用stringr包的str_extract提取每个向量元素的第一个单词
  2. 构建正则匹配模式:将首词用|拼接,实现“匹配任意一个首词”的逻辑
  3. 筛选数据框:结合dplyr的filter和str_detect完成筛选

完整代码

library(dplyr)
library(stringr)

# 提取目标向量的所有首词
first_words <- str_extract(target_vector, "^\\w+")

# 筛选col_1包含任意首词的条目
filtered_data <- Data %>% 
  filter(str_detect(col_1, paste(first_words, collapse = "|")))

print(filtered_data)

输出结果

col_1 col_2
1 Orange juice  food
2  Orange cake  food
3   Lemon curd  food
4    Lemon pie  food

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 09:01:00