【问题标题】:Change value of words in bing lexicon更改必应词典中单词的值
【发布时间】:2020-08-05 02:08:03
【问题描述】:

我正在使用 R Studio 分析一项调查。我正在使用 tidytext 包中的 Bing Sentiment 词典来执行此操作。

有些词对我的调查没有正确的含义,特别是“温柔”被编码为正面,但我的受访者将“温柔”表示为负面(疼痛)。我知道如何从 bing tibble 中删除一个词,然后添加一个新词,但我怎样才能简单地改变这个词的含义呢?

例如:

structure(list(word = c("pain", "tender", "sensitive", "headaches", 
"like", "anxiety"), sentiment = c("negative", "positive", "positive", 
"negative", "positive", "negative"), n = c(351L, 305L, 279L, 
220L, 200L, 196L)), row.names = c(NA, 6L), class = "data.frame")

我希望它看起来像:

structure(list(word = c("pain", "tender", "sensitive", "headaches", 
"like", "anxiety"), sentiment = c("negative", "negative", "positive", 
"negative", "positive", "negative"), n = c(351L, 305L, 279L, 
220L, 200L, 196L)), row.names = c(NA, 6L), class = "data.frame")

谢谢!

【问题讨论】:

  • 如果您包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出,则更容易为您提供帮助。
  • 你可以做类似df$sentiment <- ifelse(df$word == "tender", "positive", df$sentiment)的事情。
  • @MrFlick 我想我已经做了一个可重现的例子!
  • @Phil 这工作得很好!您想将此添加为答案,以便我关闭 Q 吗?

标签: r nlp tidytext lexicon


【解决方案1】:

跑线

df$sentiment <- ifelse(df$word == "tender", "positive", df$sentiment)

对于word 向量为“温柔”的任何实例,将有效地更改sentiment 向量,使其显示为“正”。任何其他实例都将保持原样。

请注意,如果您还想将其他词语的情绪改为正面,您可以这样做:

df$sentiment <- ifelse(df$word %in% c("tender", "anotherword", "etc"), "positive", df$sentiment)

【讨论】:

    【解决方案2】:

    tidyversetidytext 构建的基础上)中进行这种重新编码的方法通常是:

    library(tidyverse)
      
    df %>% 
      mutate(sentiment = case_when(
        word == "tender" ~ "negative",
        TRUE ~ sentiment # means leave if none of the conditions are met
      ))
    #>        word sentiment   n
    #> 1      pain  negative 351
    #> 2    tender  negative 305
    #> 3 sensitive  positive 279
    #> 4 headaches  negative 220
    #> 5      like  positive 200
    #> 6   anxiety  negative 196
    

    case_when 遵循与ifelse 相同的逻辑,但您可以根据需要评估任意多个条件,从而完美地重新编码多个值。 ~ 的左侧评估一个条件,如果满足该条件,则右侧说明该值。您可以设置默认值,如case_when 中的最后一行所示。

    【讨论】:

      猜你喜欢
      • 2021-10-09
      • 1970-01-01
      • 2018-02-13
      • 1970-01-01
      • 2022-12-09
      • 1970-01-01
      • 1970-01-01
      • 2018-09-22
      • 1970-01-01
      相关资源
      最近更新 更多