根据其他列中的现有单词,逐行计算字符串中单词的出现次数

时间:2019-06-11 12:34:33

标签: r nlp text-mining

我有一个包含字符串行的数据框。我想根据列中出现的单词来计算行中单词的出现。如何使用下面的代码实现这一目标? 可以通过以下方式修改以下代码来实现此目的,还是有人可以建议不需要循环的另一段代码 ?提前非常感谢!

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 个答案:

答案 0 :(得分:4)

使用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

答案 1 :(得分:2)

这是一个想法,循环遍历唯一的单词,然后使用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