code:
setwd("/Users/naifeipan")
news_us.v <- read_file('news_us.txt')
news_us.lines.v <- unlist(strsplit(news_us.v, split = '\n'))
news_us.lines.v = gsub("\r", "", news_us.lines.v)
news_us.lines.v
news_us.df <- data_frame(prez = 'news', lines = news_us.lines.v) %>%
mutate(line_id = row_number()) %>%
unite(doc_id, prez, line_id, remove = FALSE) %>%
unnest_tokens(word, lines)
news_us.df
get_sentiments("afinn")
get_sentiments("bing")
get_sentiments("nrc")
afinn <- news_us.df %>% inner_join(get_sentiments("afinn")) %>% group_by(index = line_id) %>%
summarise(sentiment = sum(score))%>% mutate(method = "AFINN")
bing_and_nrc <- bind_rows(news_us.df %>% inner_join(get_sentiments("bing")) %>%
mutate(method = "Bing et al."), news_us.df %>%
inner_join(get_sentiments("nrc") %>%
filter(sentiment %in% c("positive","negative")))%>%
mutate(method = "NRC")) %>%
count(method, index = line_id ,sentiment)%>%
spread(sentiment,n,fill = 0)%>%mutate(sentiment = positive - negative)
bind_rows(afinn, bing_and_nrc)%>%ggplot(aes(index,sentiment, fill = method)) +
geom_col(show.legend = FALSE) + facet_wrap (~method, ncol=1,scales = "free_y")
par(mfrow=c(1,1))
下面是图: