问题
I have a dataframe with rows of text. I would like to extract for each row of text a vector of specific emotion which will be a binary 0 is not exist this emotion or 1 is exist.
Totally they are 5 emotions but I would like to have the 1 only for the emotion which seem to be the most.
Example of what I have tried:
library(tidytext)
text = data.frame(id = c(11,12,13), text=c("bad movie","good movie","I think it would benefit religious people to see things like this, not just to learn about our home, the Universe, in a fun and easy way, but also to understand that non- religious explanations don't leave people hopeless and",))
nrc_lexicon <- get_sentiments("nrc")
Example of expected output:
id text sadness anger joy love neutral
11 "bad movie" 1 0 0 0 0
12 "good movie" 0 0 1 0 0
Any hints will be helpful for me.
Example to make it for every row what is the next step?
How can I call every line with the nrc lexicon analysis?
for (i in 1:nrow(text)) {
(text$text[i], nrc_lexicon)
}
回答1:
What about this:
library(tidytext) # library for text
library(dplyr)
# your data
text <- data.frame(id = c(11,12,13),
text=c("bad movie","good movie","I think it would benefit religious
people to see things like this, not just to learn about our home,
the Universe, in a fun and easy way, but also to understand that non- religious
explanations don't leave people hopeless and"), stringsAsFactors = FALSE) # here put this option, stringAsFactors = FALSE!
# the lexicon
nrc_lexicon <- get_sentiments("nrc")
# now the job
unnested <- text %>%
unnest_tokens(word, text) %>% # unnest the words
left_join(nrc_lexicon) %>% # join with the lexicon to have sentiments
left_join(text) # join with your data to have titles
Here the output with the id
, you can have it also with the titles, but I did not put it due the long third title, you can easily put it as unnested$text
in place of unnested$id
:
table_sentiment <- table(unnested$id, unnested$sentiment)
table_sentiment
anger anticipation disgust fear joy negative positive sadness surprise trust
11 1 0 1 1 0 1 0 1 0 0
12 0 1 0 0 1 0 1 0 1 1
13 0 1 0 1 1 2 3 2 1 0
And if you want it as data.frame
:
df_sentiment <- as.data.frame.matrix(table_sentiment)
Now you can do everything you want, for example, if I remember well, you want a binary output if exist or not a sentiment:
df_sentiment[df_sentiment>1]<-1
df_sentiment
anger anticipation disgust fear joy negative positive sadness surprise trust
11 1 0 1 1 0 1 0 1 0 0
12 0 1 0 0 1 0 1 0 1 1
13 0 1 0 1 1 1 1 1 1 0
来源:https://stackoverflow.com/questions/52576238/extract-emotions-calculation-for-every-row-of-a-dataframe