一个tibble的情感分析

3
基于http://tidytextmining.com/sentiment.html#the-sentiments-dataset,我正在尝试对一个tibble进行情感分析。
设置tibble:
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,类似于?

enter image description here

源代码 http://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
1个回答

2
错误/警告的主要原因是数据集中已经存在'n'列,导致在应用count时将列名更改为'nn',因为默认情况下count会创建一个'n'列。
res %>% inner_join(get_sentiments("bing")) %>% count(url, index=n, sentiment)
#通过"word"连接 # 一个tibble: 2 x 4 # url index sentiment nn # #1 t1 1 negative 1 #2 t2 1 positive 1
在随后的步骤中,我们正在使用指定为'n'的列名称来进行'spread'到“宽”格式,这与'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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接