I have a list of word and phrases and I would like create a DB that select that word and add in a column, not delete but add. This is how I want do, how can I do?
library(dplyr)
library(tidyr)
| Heading 1 |
|---------------------|
| Hello world |
| Say world|
| Say something|
tibble(
"Hello world",
"Say world",
"Say something"
)
list_of_words <- tolower(c("world","something"))
| Heading 1 | Heading 2 |
|---------------------|---------------------|
| Hello world | world |
| Say world| world|
| Say something| something|
CodePudding user response:
You could use regmatches
like this:
DB <- data.frame(heading_1 = c("Hello world", "Say world", "Say something"))
DB
#> heading_1
#> 1 Hello world
#> 2 Say world
#> 3 Say something
list_of_words <- tolower(c("world","something"))
words <- paste(list_of_words, collapse="|")
DB$heading_2 <- unlist(regmatches(DB$heading_1, gregexpr(words, DB$heading_1)))
DB
#> heading_1 heading_2
#> 1 Hello world world
#> 2 Say world world
#> 3 Say something something
Created on 2022-07-21 by the reprex package (v2.0.1)