Insert vector value in column(test_condition), if this word is contained in the sentence in the the according row

Viewed 45

I'm relatively new to R and got stuck with the following problem:

I have this vector:

condition<-c('hello','hi','bye', 'see you', 'Good morning')

The value of this vector should be inserted into the column test_condition if it is contained in the column sentence in the same row.

this would be the data frame

sentence<-c('hi,whats going on','hello, how r you','next','Nice, see you tmrw','Good morning dear')
df<-as.data.frame(sentence) %>%
  add_column(test_condition=NA)

and this is what the result would look like

desired results

Does someone know how to solve this?

2 Answers

Does this work:

> library(stringr)
> library(dplyr)
> df$condition <- str_extract(df$sentence, paste0(condition, collapse = '|'))
> df
            sentence    condition
1  hi,whats going on           hi
2   hello, how r you        hello
3               next         <NA>
4 Nice, see you tmrw      see you
5  Good morning dear Good morning

Data used:

> condition<-c('hello','hi','bye', 'see you', 'Good morning')
> sentence<-c('hi,whats going on','hello, how r you','next','Nice, see you tmrw','Good morning dear')
> df <- data.frame(sentence = sentence, stringsAsFactors = F)
> df
            sentence
1  hi,whats going on
2   hello, how r you
3               next
4 Nice, see you tmrw
5  Good morning dear

Does this what you want? I included the possibility that case would not match, or that multiple conditions may be met.

library(tidyverse)

sentence<-c('hi, whats going on', 'hello, how r you', 'next',
            'Nice, see you tmrw','Good morning dear', 
            'Hi, hello, hi, nice morning')

df<-as.data.frame(sentence) %>% add_column(test_condition=NA)

condition<-c('hello','hi','bye', 'see you', 'Good morning')

fnc <- function(xsentence) {
  idx <- sapply(condition, FUN = function(xcond) {
    grepl(pattern = xcond, xsentence, ignore.case = TRUE)})
  if (!any(idx)) {return(NA)}
  else {return(paste(condition[idx], collapse = ", "))}
}

df$test_condition <- sapply(sentence, FUN = fnc)
df
                     sentence test_condition
1          hi, whats going on             hi
2            hello, how r you          hello
3                        next           <NA>
4          Nice, see you tmrw        see you
5           Good morning dear   Good morning
6 Hi, hello, hi, nice morning      hello, hi
Related