r - 如何从单词列表中查找 DF 中的匹配单词并在新列中返回匹配的单词
问题描述
我有一个 2 列的 DF,我有一个单词列表。
list_of_words <- c("tiger","elephant","rabbit", "hen", "dog", "Lion", "camel", "horse")
df <- tibble::tibble(page=c(12,6,9,18,2,15,81,65),
text=c("I have two pets: a dog and a hen",
"lion and Tiger are dangerous animals",
"I have tried to ride a horse",
"Why elephants are so big in size",
"dogs are very loyal pets",
"I saw a tiger in the zoo",
"the lion was eating a buffalo",
"parrot and crow are very clever birds"))
animals <- c("dog,hen", "lion,tiger", "horse", FALSE, "dog", "tiger", "lion", FALSE)
cbind(df, animals)
#> page text animals
#> 1 12 I have two pets: a dog and a hen dog,hen
#> 2 6 lion and Tiger are dangerous animals lion,tiger
#> 3 9 I have tried to ride a horse horse
#> 4 18 Why elephants are so big in size FALSE
#> 5 2 dogs are very loyal pets dog
#> 6 15 I saw a tiger in the zoo tiger
#> 7 81 the lion was eating a buffalo lion
#> 8 65 parrot and crow are very clever birds FALSE
我需要找出列表中的任何单词是否存在于 DF 的一列中。如果是,则将单词/单词返回到 DF 中的新列。这是单词列表 ->(tiger,elephant,rabbit, hen, dog, Lion, camel, horse)。 这就是我的 DF 看起来 我想要这样的东西
解决方案
library(dplyr)
df %>%
rowwise() %>%
mutate(animals = paste(list_of_words[unlist(
lapply(list_of_words, function(x) grepl(x, text, ignore.case = T)))], collapse=",")) %>%
data.frame()
输出是:
page text animals
1 12 pets: dog & hen hen,dog
2 6 Lions and tigers are dangerous animal tiger,Lion
3 9 I have tried to ride a horse horse
4 65 parrot & crow are very clever birds
样本数据:
df <- structure(list(page = c(12, 6, 9, 65), text = structure(c(4L,
2L, 1L, 3L), .Label = c("I have tried to ride a horse", "Lions and tigers are dangerous animal",
"parrot & crow are very clever birds", "pets: dog & hen"), class = "factor")), .Names = c("page",
"text"), row.names = c(NA, -4L), class = "data.frame")
list_of_words <- c("tiger", "elephant", "rabbit", "hen", "dog", "Lion", "camel", "horse")
**另一种方法:**
library(data.table)
setDT(df)[, animals := paste(list_of_words[unlist(lapply(list_of_words, function(x) grepl(x, text, ignore.case = T)))], collapse = ","), by = 1:nrow(df)]
#> df
# page text animals
#1: 12 pets: dog & hen hen,dog
#2: 6 Lions and tigers are dangerous animal tiger,Lion
#3: 9 I have tried to ride a horse horse
#4: 65 parrot & crow are very clever birds
推荐阅读
- java - 如何在代码中在 Spring Boot 中配置 Flyway
- android - Flutter AR - 绘制平面
- php - 在我自己的网站中的嵌入式 youtube 视频中设置时间线
- hyperledger-fabric - 如何安装 Fabric Mir BFT 共识?
- python - 计算数据框中列表长度的乘积并存储在新列中
- rxjs - 订阅方法中的可观察取消订阅
- azure-active-directory - 通过 API 创建 Microsoft 团队会议
- wordpress - Gantry 5 中的响应块大小
- c++ - C++ 这个函数会导致未定义的行为吗?
- javascript - Javascript中的Django模板变量