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

如何检查数据框列中的句子是否包含特定单词?

检查数据框列中是否存在特定单词的方法

嘿,我来帮你搞定这个需求!根据你描述的场景(列里是类似c("Animation", "Comedy", "Family")的内容),分两种常见情况给你解决方案:

情况1:列是列表列(每个元素是字符向量)

如果你的数据框列是列表类型(比如每行的genre是一个包含多个类型的向量),可以用purrr包的map_lgl函数快速判断:

# 先加载purrr(没装的话先运行install.packages("purrr"))
library(purrr)

# 给数据框新增一列,标记每行是否包含"Animation"
df$has_animation <- map_lgl(df$genre, ~ "Animation" %in% .x)

这里的~ "Animation" %in% .x是对每行的genre向量做检查,返回TRUE/FALSE结果。

情况2:列是逗号分隔的字符串列

如果列里的每个元素是单个字符串(比如"Animation, Comedy, Family"),用正则表达式或者stringr包更方便:

Base R 原生方法

# 用grepl做精确单词匹配(\\b是单词边界,避免误匹配类似"AnimationXYZ"的字符串)
df$has_animation <- grepl("\\bAnimation\\b", df$genre, ignore.case = FALSE)

stringr 更直观的写法

# 先安装加载stringr:install.packages("stringr")
library(stringr)

# fixed()做精确匹配,不启用正则,更快更安全
df$has_animation <- str_detect(df$genre, fixed("Animation"))

扩展:检查多个特定单词

如果要同时检查是否包含"Animation"或"Comedy",可以这样写:

  • 列表列场景:
df$has_target <- map_lgl(df$genre, ~ any(c("Animation", "Comedy") %in% .x))
  • 字符串列场景:
df$has_target <- str_detect(df$genre, fixed("Animation") | fixed("Comedy"))

这样就能轻松标记出包含目标单词的行啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:10:27