Посчитайте вхождения слов в строке строк на основе существующих слов в других столбцах - PullRequest
4 голосов
/ 11 июня 2019

У меня есть фрейм данных, в котором есть строки строк.Я хочу посчитать вхождение слов в строках в зависимости от того, какие слова появляются в столбце.Как я могу добиться этого с помощью кода ниже? Можно ли каким-либо образом изменить приведенный ниже код для достижения этой цели или кто-нибудь может предложить другой фрагмент кода, который не требует циклов ?Большое спасибо заранее!

df <- data.frame(
  words = c("I want want to compare each ",
            "column to the values in",
            "If any word from the list any",
            "replace the word in the respective the word want"),
  want= c("want", "want", "want", "want"),
  word= c("word", "word", "word", "word"),
  any= c("any", "any", "any", "any"))

#add 1 for match and 0 for no match
for (i in 2:ncol(df))
{
  for (j in 1:nrow(df))
  {                 
    df[j,i] <- ifelse (grepl (df[j,i] , df$words[j]) %in% "TRUE", 1, 0)
  }
  print(i)
}

*'data.frame':  4 obs. of  4 variables:
 $ words: chr  "I want want to compare each " "column to the values in " "If any word from the words any" "replace the word in the respective the word"
 $ want : chr  "want" "want" "want" "want"
 $ word : chr  "word" "word" "word" "word"
 $ any  : chr  "any" "any" "any" "any"*

Вывод должен выглядеть следующим образом:

    words                                                 want word any
1   I want want to compare each                            2    0   0
2   column to the values in                                0    0   0
3   If any word from the list any                          0    1   2
4   replace the word in the respective the word want       1    2   0

Токовый вывод с существующим кодом выглядит следующим образом:

    words                                                 want word any
1   I want want to compare each                            1    0   0
2   column to the values in                                0    0   0
3   If any word from the list any                          0    1   1
4   replace the word in the respective the word want       1    1   0

Ответы [ 2 ]

4 голосов
/ 11 июня 2019

При tidyverse (небольшое нарушение синтаксиса при использовании $):

library(tidyverse)

df %>% 
     mutate_at(vars(-words),function(x) str_count(df$words,x))
                                             words want word any
1                     I want want to compare each     2    0   0
2                          column to the values in    0    0   0
3                    If any word from the list any    0    1   2
4 replace the word in the respective the word want    1    2   0

или при использовании modify_at, и, как предлагает @Sotos, мы можем использовать . для поддержания tidyverseсинтаксис.

df %>% 
      modify_at(2:ncol(.),function(x) str_count(.$words,x))
                                             words want word any
1                     I want want to compare each     2    0   0
2                          column to the values in    0    0   0
3                    If any word from the list any    0    1   2
4 replace the word in the respective the word want    1    2   0
2 голосов
/ 11 июня 2019

Вот идея, циклически перебирающая уникальные слова для подсчета и использующая для подсчета пакет str_count из stringr, т.е.

sapply(unique(unlist(df[-1])), function(i) stringr::str_count(df$words, i))

#     want word any
#[1,]    2    0   0
#[2,]    0    0   0
#[3,]    0    1   2
#[4,]    1    2   0
...