【发布时间】:2022-01-03 17:24:11
【问题描述】:
我想将单词列表中的单词与文本匹配并将它们提取到新列中。
我有这个数据
df <- structure(list(ID = 1:3, Text = c(list("red car, car going, going to"), list("red ball, ball on, on street"), list("to be, be or, or not"))), class = "data.frame", row.names = c(NA, -3L))
ID Text
1 1 red car, car going, going to
2 2 red ball, ball on, on street
3 3 to be, be or, or not
还有我这个重要的单词列表
words <- c("car", "ball", "street", "dog", "frog")
我想要这样的df
ID Text Word
1 1 red car, car going, going to c("car","car")
2 2 red ball, ball on, on street c("ball", "ball", "street")
3 3 to be, be or, or not NA
我的尝试
df$Word <- lapply(df$Text, function(x) stringr::str_extract_all(x, "\\b"%s+%words+%"\\b"))
但它给了我一个长度为 5 的列表,而不仅仅是来自 Text 的单词。
【问题讨论】:
-
为什么第二行只有一个
ball,而第一行有两个car? -
对不起,我的错误。
标签: r string string-matching