【问题标题】:Sentiment analysis on a tibble微博上的情绪分析
【发布时间】:2023-03-16 21:46:01
【问题描述】:

基于http://tidytextmining.com/sentiment.html#the-sentiments-dataset,我正在尝试对小标题进行情绪分析。

设置小标题:

url <- c( "t1" , "t2")
word <- c( "abnormal" , "good")
n <- c( 1 , 1)
score <- c(1 , 2)
res <- as_tibble(data.frame("url"=url , "word"=word, "n"=n , "score"=score , stringsAsFactors = F))
res

创建:

# A tibble: 2 x 4
    url     word     n score
  <chr>    <chr> <dbl> <dbl>
1    t1 abnormal     1     1
2    t2     good     1     2

产生情绪:

joined_sentiments <- res %>% inner_join(get_sentiments("bing"))
joined_sentiments

创建:

# A tibble: 2 x 5
    url     word     n score sentiment
  <chr>    <chr> <dbl> <dbl>     <chr>
1    t1 abnormal     1     1  negative
2    t2     good     1     2  positive

然后我怎样才能将这些转换为一系列图表,其中每个图表都是一个特定的 url,类似于

srchttp://tidytextmining.com/sentiment.html#the-sentiments-dataset

由于没有行号,我正在尝试:

joined_sentiments %>%
  count(url, index=n, sentiment) %>%
  spread(sentiment, n, fill = 0) %>%
  mutate(sentiment = positive - negative)

返回错误:

joined_sentiments %>%
+   count(url, index=n, sentiment) %>%
+   spread(sentiment, n, fill = 0) %>%
+   mutate(sentiment = positive - negative)
Error: `var` must evaluate to a single number or a column name, not a double vector
In addition: Warning message:
In if (!is.finite(x)) return(FALSE) :
  the condition has length > 1 and only the first element will be used

【问题讨论】:

    标签: r


    【解决方案1】:

    错误/警告的主要原因是数据集中已经存在'n'列,导致当count应用为count时列名更改为'nn'默认创建一个'n ' 列。

    分辨率 %>% inner_join(get_sentiments("bing")) %>% 计数(网址,索引=n,情绪)
    #Joining, by = "word" # 一个小标题:2 x 4 # url 索引情绪 nn # #1 t1 1 负 1 #2 t2 1 正 1

    在后续步骤中,我们将spreading 转换为“宽”格式,列名指定为“n”,与“nn”不匹配。所以要么把它改成'nn'

    res1 <- res %>% 
              inner_join(get_sentiments("bing")) %>% 
              count(url, index=n, sentiment) %>% 
              spread(sentiment, nn, fill = 0) %>%
              mutate(sentiment = positive - negative)
    res1
    #Joining, by = "word"
    # A tibble: 2 x 5
    #     url index negative positive sentiment
    #   <chr> <dbl>    <dbl>    <dbl>     <dbl>
    #1    t1     1        1        0        -1
    #2    t2     1        0        1         1
    

    然后用ggplot,就可以了(用两行数据,输出可能不好看)

    ggplot(res1, aes(index, sentiment, fill = url)) +
         geom_col(show.legend = FALSE) +
         facet_wrap(~url, ncol = 2, scales = "free_x")
    

    或在创建“res”时删除列“n”,然后 OP 的原始代码就可以正常工作了

    res <- tibble(url , word, score)
    

    【讨论】:

      猜你喜欢
      • 2013-02-02
      • 2021-09-06
      • 2014-12-11
      • 1970-01-01
      • 1970-01-01
      • 2011-05-10
      • 2013-02-07
      • 2021-04-29
      • 2019-10-06
      相关资源
      最近更新 更多