Вставить векторное значение в столбец (test_condition), если это слово содержится в предложении в соответствующей строке

#r

#r

Вопрос:

Я относительно новичок в R и застрял со следующей проблемой:

У меня есть этот вектор:

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

Значение этого вектора должно быть вставлено в столбец test_condition , если оно содержится в столбце sentence в той же строке.

это будет фрейм данных

 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)
  

и вот как будет выглядеть результат

желаемые результаты

Кто-нибудь знает, как это решить?

Ответ №1:

Работает ли это:

 > 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
  

Используемые данные:

 > 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
  

Комментарии:

1. Большое спасибо, str_extract — это именно то, что мне было нужно для этого!

Ответ №2:

Это то, что вы хотите? Я включил возможность того, что регистр не будет совпадать или что может быть выполнено несколько условий.

 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