我想將單詞串列中的單詞與文本匹配并將它們提取到一個新列中。
我有這個資料
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 的單詞。
uj5u.com熱心網友回復:
一個可能的解決方案:
library(tidyverse)
df <- data.frame(
stringsAsFactors = FALSE,
ID = c(1L, 2L, 3L),
Text = c("red car, car going, going to","red ball, ball on, on street",
"to be, be or, or not")
)
words <- c("car", "ball", "street", "dog", "frog")
df %>%
mutate(word = Text) %>%
separate_rows(word, sep = ",|\\s") %>%
mutate(word = ifelse(word %in% words, word, NA)) %>%
drop_na(word) %>%
group_by(ID) %>%
summarise(word = str_c(word, collapse = ", "), .groups = "drop") %>%
left_join(df,., by=c("ID"))
#> ID Text word
#> 1 1 red car, car going, going to car, car
#> 2 2 red ball, ball on, on street ball, ball, street
#> 3 3 to be, be or, or not <NA>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/365673.html
上一篇:排序軸并使資料更具表現力
