R 如何在新列中获得 afinn 分数

R how get afinn score in a new column

这是我的问题。 我想将与一列单个单词相关的“AFINN”分数放入另一列 这是我的数据集

head(service_df)
# A tibble: 6 x 3
  word1   word2        n
  <chr>   <chr>    <int>
1 service delivery  8574
2 service covid     1163
3 service lockdown   541
4 service worker     389
5 service provider   370
6 service online     236

我想获得与“word2”列相关的分数,以便有这样的东西

   word1   word2        n      AFINN_word_2
      <chr>   <chr>    <int>
    1 service delivery  8574    -1
    2 service covid     1163     0
    3 service lockdown   541     0  
    4 service worker     389     0.3
    5 service provider   370     0.1
    6 service online     236     1

(我只是把随机值放在AFINN_word_2下面)

谢谢大家!

不幸的是,您 none 在示例中提供的记录与归因于 afinn 情感分数的词相匹配。您可以尝试标记化或重新编码您在 words2 中的单词。

# Install pacakges if they are not already installed: necessary_packages => vector
necessary_packages <- c("tidytext", "tidyverse")

# Create a vector containing the names of any packages needing installation:
# new_pacakges => vector
new_packages <- necessary_packages[!(necessary_packages %in%
                                       installed.packages()[, "Package"])]

# If the vector has more than 0 values, install the new pacakges
# (and their) associated dependencies:
if(length(new_packages) > 0){install.packages(new_packages, dependencies = TRUE)}

# Initialise the packages in the session: list of boolean => stdout (console)
lapply(necessary_packages, require, character.only = TRUE)

# data: service_df => data.frame
service_df <- structure(list(word1 = c("service", "service", "service", "service", 
"service", "service"), word2 = c("delivery", "covid", "lockdown", 
"worker", "provider", "online"), n = c(8574L, 1163L, 541L, 389L, 
370L, 236L)), class = "data.frame", row.names = c(NA, -6L))

# Use afinn to get sentiment of word: res => data.frame
res <- service_df %>%
  left_join(get_sentiments("afinn"), by = c("word2" = "word")) %>%
  select(word1, word2, n, AFINN_word_2 = value)