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

如何筛选tibble中向量元素属于指定单词集的行?

解决方案

首先构造你的示例数据(确保tags列为列表格式,这是处理这类嵌套向量的关键):

library(tibble)
df <- tibble(
  tags = list(
    c("hello", "hi"),
    c("blanks", "nothing"),
    c("thanks", "welcome"),
    "hi"
  )
)
filtered_words <- c("hi","bye","thanks")

你遇到的问题是直接用filter(tags %in% filtered_words)会返回多个逻辑值,导致筛选失败。需要对每行的tags向量做是否存在至少一个匹配元素的判断,将多行逻辑值压缩为单个TRUE/FALSE,再传给filter。

方法1:结合dplyr和purrr

用purrr::map_lgl遍历tags列的每个元素,返回单个逻辑值供filter使用:

library(dplyr)
library(purrr)

df_filtered <- df %>%
  filter(map_lgl(tags, ~ any(.x %in% filtered_words)))

方法2:用base R的sapply替代purrr

如果不想加载purrr包,用base R的sapply也能实现同样效果:

library(dplyr)

df_filtered <- df %>%
  filter(sapply(tags, function(x) any(x %in% filtered_words)))

两种方法都会保留第1、3、4行,符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 02:35:19