如何获取列表列中包含元素的行

How to get rows with elements in the list column

我有一个 数据表 如下:

library(data.table)

dt <- data.table(
  id = c(1:3),
  string = list(c("tree", "house", "star"),  
                c("house", "tree", "dense forest"), 
                c("apple", "orange", "grapes"))
  )

由此我想在列表字符串列中获取包含 "tree" 的行。 所以我尝试了

dt["tree" %in% string]
Empty data.table (0 rows) of 2 cols: id,string


dt["tree" %in% unlist(string)]
   id                  string
1:  1         tree,house,star
2:  2 house,tree,dense forest
3:  3     apple,orange,grapes

我不确定我在做什么 wrong.I 只需要 id 1 和 2 returned.Any 感谢帮助。

由于 string 是一个列表,您需要 sapply 或其他一些方法来遍历每个列表。

library(data.table)
dt[sapply(string, function(x) any(x == "tree"))]

#   id                  string
#1:  1         tree,house,star
#2:  2 house,tree,dense forest

或者只是

library(data.table)
dt[grep("\btree\b", string)]

   id                  string
1:  1         tree,house,star
2:  2 house,tree,dense forest

看来你的方法有问题 %in% 不适用于列表

"tree" %in% dt$string[1]
[1] FALSE

grep()grepl() 接受它可以强制转换为字符向量的所有内容

grepl("tree", dt$string[1])
[1] TRUE

as.character(dt$string[1])
[1] "c(\"tree\", \"house\", \"star\")"

这意味着它还会将其他单词与 IF 中的 tree 匹配为@RonakShah 提醒我你不要使用单词边界 \b.

我们还可以使用 str_detect 来自 stringr

library(dplyr)
library(stringr)
dt %>%
   filter(str_detect(string, "\btree\b"))
#   id                    string
#1  1         tree, house, star
#2  2 house, tree, dense forest

或在data.table

中使用Map
dt[unlist(Map(`%in%`, "tree", string))]
#   id                  string
#1:  1         tree,house,star
#2:  2 house,tree,dense forest