【问题标题】:Converting data frame to tibble with word count使用字数将数据帧转换为 tibble
【发布时间】:2018-05-16 18:09:26
【问题描述】:

我正在尝试基于 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 出现次数的新列。相同的 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,因为这似乎是 tidytextmining 情绪分析所需的格式:http://tidytextmining.com/sentiment.html#the-sentiments-dataset

【问题讨论】:

  • 为什么要转换tibble?换句话说,您的标题似乎并不代表实际问题。看来您只希望每个 url 有一个单词。我认为一种可能的 tibbliverse 方法可能是 res %&gt;% group_by(url) %&gt;% transform(text = strsplit(text, " ", fixed = TRUE)) %&gt;% unnest() %&gt;% count(url, text)(假设 text 是一个字符串而不是一个因素)
  • @DavidArenburg 请查看更新

标签: r dataframe tibble tidytext


【解决方案1】:

您正在寻找这样的东西吗?当你想用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-15
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多