Номера столбцов аргументов не совпадают - PullRequest
0 голосов
/ 12 июня 2018

Я использую этот пример для проведения анализа настроений коллекции текстовых документов в R. Код:

library(tm)
library(tidyverse)
library(tidytext)
library(glue)
library(stringr)
library(dplyr)
library(wordcloud)
require(reshape2)

files <- list.files(inputdir,pattern="*.txt")

GetNrcSentiment <- function(file){

    fileName <- glue(inputdir, file, sep = "")
    fileName <- trimws(fileName)
    fileText <- glue(read_file(fileName))
    fileText <- gsub("\\$", "", fileText) 

    tokens <- data_frame(text = fileText) %>% unnest_tokens(word, text)

    # get the sentiment from the first text: 
    sentiment <- tokens %>%
        inner_join(get_sentiments("nrc")) %>% # pull out only sentiment words
        count(sentiment) %>% # count the # of positive & negative words
        spread(sentiment, n, fill = 0) %>% # made data wide rather than narrow
        mutate(sentiment = positive - negative) %>% # positive - negative
        mutate(file = file) %>% # add the name of our file
        mutate(year = as.numeric(str_match(file, "\\d{4}"))) %>% # add the year
        mutate(city = str_match(file, "(.*?).2")[2]) 

    return(sentiment)
}

.TXT-файлы хранятся в inputdirи имеют имена AB-City.0000, где AB - это сокращение страны, City - название города, а 0000 - год (в диапазоне от 2000 до 2017).

Функция работает для одного файла, как и ожидалось, т.е.GetNrcSentiment(files[1]) дает мне надобность с правильными подсчетами на настроение.Однако, когда я пытаюсь запустить его для всего набора, то есть

nrc_sentiments  <- data_frame()

for(i in files){
    nrc_sentiments <- rbind(nrc_sentiments, GetNrcSentiment(i))
}

, я получаю следующее сообщение об ошибке:

Joining, by = "word"
Error in rbind(deparse.level, ...) : 
  numbers of columns of arguments do not match

Точно такой же код хорошо работает с более длинными документами, новыдает ошибку при работе с более короткими текстами.Кажется, что не все настроения обнаруживаются в небольших документах, и в результате количество столбцов для каждого документа различается, что может привести к этой ошибке, но я не уверен.Буду признателен за любые советы о том, как решить проблему.Если настроение не найдено, я бы хотел, чтобы запись была равна нулю (если это является причиной моей проблемы).

Кроме того, функция bing sentiment просматривает около двух десятков файлов и даетдругая ошибка, которая, кажется, указывает на ту же проблему (отрицательное чувство не найдено?):

GetBingSentiment <- function(file){
    fileName <- glue(inputdir, file, sep = "")
    fileName <- trimws(fileName)

    fileText <- glue(read_file(fileName))
    fileText <- gsub("\\$", "", fileText)       
    tokens <- data_frame(text = fileText) %>% unnest_tokens(word, text)

    # get the sentiment from the first text: 
    sentiment <- tokens %>%
        inner_join(get_sentiments("bing")) %>% # pull out only sentiment words
        count(sentiment) %>% # count the # of positive & negative words
        spread(sentiment, n, fill = 0) %>% # made data wide rather than narrow
        mutate(sentiment = positive - negative) %>% 
        mutate(file = file) %>% # add the name of our file
        mutate(year = as.numeric(str_match(file, "\\d{4}"))) %>% # add the year
        mutate(city = str_match(file, "(.*?).2")[2])

    # return our sentiment dataframe
    return(sentiment)
}

Error in mutate_impl(.data, dots) : 
  Evaluation error: object 'negative' not found. 

РЕДАКТИРОВАТЬ: Следуя рекомендации Дэвида Клоца, я отредактировал код до

for(i in files){ nrc_sentiments <- dplyr::bind_rows(nrc_sentiments, GetNrcSentiment(i)) } 

В результате, вместо выдачи ошибки, nrc генерирует NA, если слова из определенного настроения не найдены, однако после 22 присоединений я получаю другую ошибку:

Error in mutate_impl(.data, dots) : Evaluation error: object 'negative' not found.

Та же ошибка появляется при запуске функции bing с помощью dplyr.Оба кадра данных к моменту достижения функциями 22-го документа содержат столбцы для всех настроений.Что может вызвать ошибку и как ее диагностировать?

Ответы [ 2 ]

0 голосов
/ 13 июня 2018

На входе может отсутствовать «отрицательный» столбец, который используется в выражении

0 голосов
/ 12 июня 2018
Функция

dplyr bind_rows более гибкая, чем rbind, по крайней мере, когда речь идет о пропущенных столбцах:

nrc_sentiments <- dplyr::bind_rows(nrc_sentiments, GetNrcSentiment(i))
...