【问题标题】:How do I iterate over rows in a dataframe to detect different words and save it in a new column?如何遍历数据框中的行以检测不同的单词并将其保存在新列中?
【发布时间】:2017-12-13 12:56:26
【问题描述】:

我一直在尝试编写一个函数或使用 apply 系列来选择数据框中包含我要查找的单词的行并将它们标记为标签。一行可以有多个标签。有人可以帮助我吗,我已经卡了一段时间了。

如果我的问题不清楚,或者在其他地方有答案,请引导我朝着正确的方向前进。非常感激!

require(stringr)
require(dplyr)
df <- data.frame(sentences, rnorm(length(sentences)))

old = df %>% filter(str_detect(sentences, 'old')) %>% mutate(w = factor("old"))
new = df %>% filter(str_detect(sentences, 'new')) %>% mutate(w = factor("new"))
boy = df %>% filter(str_detect(sentences, 'boy')) %>% mutate(w = factor("boy"))
girl = df %>% filter(str_detect(sentences, 'girl')) %>% mutate(w = factor("girl"))
tags <- bind_rows(old, new, boy, girl)

所以我想选择有限数量的单词,例如:

tags <- c('bananas', 'apples', oranges)

我希望结果是一个 data.frame,其中包含我选择的每个单词的新列。如果该行包含我选择的单词之一,则该单词的列应以某种方式标记为 TRUE och。类似的东西

Sentences     bananas     apples     oranges  
sentence1     TRUE        
sentence2                 TRUE
sentence3     TRUE
sentence4                            TRUE
sentence5                 TRUE       TRUE

Sentences     tag1        tag2
sentence1     bananas        
sentence2     apples
sentence3     bananas
sentence4     oranges
entences5     apples      oranges

或者类似的东西。如果我能解释得更清楚,请告诉我。

【问题讨论】:

  • 您正在寻找的最终解决方案是什么?从概念上讲,它可以做什么?
  • 您尝试标记的单词数量是否有限?
  • 我试图解释更多,单词的数量是有限的,我希望每一行都被标记,如果它包含任何单词。我不知道什么可能是好的,要么是每个单词的列,要么标签 #1 #2 #3 最多(标签的 nr 个)。
  • 你能提供sentences吗?

标签: r tags stringr


【解决方案1】:

你真的想使用 apply 函数吗?我很确定 tm 包就是你要找的。这是最简单、更可靠的方法。使用DocumentTermMatrix 函数,您可以获得您想要的。我自己阐述了一些句子(句法水平很高)。最简单的方法是继续处理所有单词,然后在您拥有矩阵后选择您想要查找的单词的那些列

sentence1 <- "This is a bananana"
sentence2 <- "This is an apple"
sentence3 <- "This is a watermelon and a banana"
sentence4 <- "This is a watermelon a banana an apple"

df_sentence <- rbind(sentence1, sentence2, sentence3, sentence4)

library(tm)
vs_sentence <- VectorSource(df_sentence)
vc_sentence <- VCorpus(vs_sentence)

clean_sentence <- tm_map(vc_sentence, removePunctuation)
dtm_sentence <- DocumentTermMatrix(clean_sentence)
as.matrix(dtm_sentence)

结果:

        Terms
Docs and apple banana this watermelon
   1   0     0      1    1          0
   2   0     1      0    1          0
   3   1     0      1    1          1
   4   0     1      1    1          1

另外还有一个功能可以让你按列获取文档,按行获取词条:

as.matrix(TermDocumentMatrix(clean_sentence))
            Docs
Terms        1 2 3 4
  and        0 0 1 0
  apple      0 1 0 1
  banana     1 0 1 1
  this       1 1 1 1
  watermelon 0 0 1 1

如果您可以提供部分句子,也许会更容易为您提供更好的解决方案。 HTH!

【讨论】:

    猜你喜欢
    • 2021-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 2018-07-06
    • 2022-11-14
    • 2016-01-12
    相关资源
    最近更新 更多