Заменить для цикла с lapply - PullRequest
       2

Заменить для цикла с lapply

0 голосов
/ 12 февраля 2019

Можно ли заменить цикл for следующим образом:

library(quanteda)
library(quanteda.dictionaries)

#dummy data
df <- data.frame(text = c("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.", "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.", "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown pr

    inter took a galley of type and scrambled it to make a type specimen book."))

    for (j in 1:nrow(df)) {
        out <- liwcalike(df$text[j], 
                            dictionary = data_dictionary_NRC)
        dfm <- rbind(dfm, data.frame(em1 = out$trust, em2= out$anger))
    }

на lapply или что-нибудь еще, чтобы сократить время выполнения?

1 Ответ

0 голосов
/ 12 февраля 2019

Создайте список фреймов данных и rbind один раз вне цикла и избегайте квадратичного копирования с rbind внутри цикла:

df_list <- lapply(df$text, function(txt) {
               out <- liwcalike(txt, dictionary = data_dictionary_NRC)
               return(data.frame(em1 = out$trust, em2= out$anger, origin=txt))
           }

final_df <- do.call(rbind, df_list)

В случае каких-либо проблем с liwcalikeвызовите, оберните процесс в tryCatch, чтобы вернуть NA -строчный фрейм данных при любых ошибках:

df_list <- lapply(df$text, function(txt) {
               tryCatch({
                   out <- liwcalike(txt, dictionary = data_dictionary_NRC)
                   return(data.frame(em1=out$trust, em2=out$anger, origin=txt, error=NA))
               }, error = function(e) 
                   data.frame(em1=NA, em2=NA, origin=txt, error=e)
               )
           }

final_df <- do.call(rbind, df_list)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...