使用字数将数据帧转换为tibble

时间:2017-12-02 23:23:48

标签: r dataframe tibble tidytext

我试图根据http://tidytextmining.com/sentiment.html#the-sentiments-dataset执行情绪分析。在执行情绪分析之前,我需要将我的数据集转换为整齐的格式。

我的数据集格式为:

x <- c( "test1" , "test2")
y <- c( "this is test text1" , "this is test text2")
res <- data.frame( "url" = x, "text" = y)
res
    url               text
1 test1 this is test text1
2 test2 this is test text2

为了每行转换为一个观察,需要处理文本列并添加包含该URL的单词和次数的新列。相同的网址将出现在多行中。

这是我的尝试:

library(tidyverse)

x <- c( "test1" , "test2")
y <- c( "this is test text1" , "this is test text2")
res <- data.frame( "url" = x, "text" = y)
res

res_1 <- data.frame(res$text)
res_2 <- as_tibble(res_1)
res_2 %>% count(res.text, sort = TRUE) 

返回:

# A tibble: 2 x 2
            res.text     n
              <fctr> <int>
1 this is test text1     1
2 this is test text2     1

如何计算res $ text数据框中的单词并维护url以执行情绪分析?

更新:

x <- c( "test1" , "test2")
y <- c( "this is test text1" , "this is test text2")
res <- data.frame( "url" = x, "text" = y)
res

res %>%
group_by(url) %>%
transform(text = strsplit(text, " ", fixed = TRUE)) %>%
unnest() %>%
count(url, text) 

返回错误:

Error in strsplit(text, " ", fixed = TRUE) : non-character argument

我尝试转换为tibble,因为这似乎是整理文本分析所需的格式:http://tidytextmining.com/sentiment.html#the-sentiments-dataset

1 个答案:

答案 0 :(得分:4)

你正在寻找这样的东西吗?如果要使用tidytext包处理情绪分析,则需要将每个字符串中的单词与unnest_tokens()分开。此功能不仅可以将文本分成单词。如果你想稍后看一下这个功能。每行一个单词后,您可以使用count()计算每个单词在每个文本中出现的次数。然后,您想要删除停用词。 tidytext包有数据,所以你可以调用它。最后,您需要获得情绪信息。在这里,我选择了AFINN,但如果你愿意,你可以选择另一个。我希望这会对你有所帮助。

x <- c( "text1" , "text2")
y <- c( "I am very happy and feeling great." , "I am very sad and feeling low")
res <- data.frame( "url" = x, "text" = y, stringsAsFactors = F)

#    url                               text
#1 text1 I am very happy and feeling great.
#2 text2      I am very sad and feeling low

library(tidytext)
library(dplyr)

data(stop_words)
afinn <- get_sentiments("afinn")

unnest_tokens(res, input = text, output = word) %>%
count(url, word) %>%
filter(!word %in% stop_words$word) %>%
inner_join(afinn, by = "word")

#    url    word     n score
#  <chr>   <chr> <int> <int>
#1 text1 feeling     1     1
#2 text1   happy     1     3
#3 text2 feeling     1     1
#4 text2     sad     1    -2
相关问题