首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用lapply替换循环

用lapply替换循环
EN

Stack Overflow用户
提问于 2019-02-12 16:21:15
回答 1查看 115关注 0票数 1

是否可以替换如下的for循环:

代码语言:javascript
复制
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))
    }

以减少执行时间?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-12 16:39:54

构建一个数据帧列表,并将重新绑定一次外部循环,并避免使用rbind内部循环进行四向复制:

代码语言:javascript
复制
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-row数据帧:

代码语言:javascript
复制
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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54654458

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档