需要嵌套循环或其他方式在 R 中加入这些函数吗?

问题描述

推文是一个包含大量推文的数据框。


by(tweets,tweets$query,function(y) {
  y$stripped_text <- gsub('http\\S+\\s*',"",y$text)
  y$stripped_text <- gsub('https\\S+\\s*',y$stripped_text)
  y$stripped_text <- gsub('[[:punct:]]',y$stripped_text)
  y$stripped_text <- gsub('[[cntrl:]]',y$stripped_text)
  y$stripped_text <- gsub('\\d+',y$stripped_text)
  y$stripped_text <- gsub('@',y$stripped_text)
  y$stripped_text <- gsub('#.!',y$stripped_text)
  y$stripped_text <- gsub("[^\x01-\x7F]",y$stripped_text)
  y$stripped_text <- tolower(y$stripped_text)
  orderedy <- order(y$created_at)
  y <- y[orderedy,]
  y$created_at <- as.Date(y$created_at)
  tss <- y %>% select(created_at,stripped_text,retweet_count,favorite_count,query)
  tss$cleaned_text <- tss$stripped_text
  tss <- tss %>% select(-stripped_text)
  tss <- cbind(Uni_ID_Tweet = rownames(tss),tss)
  tssBYWORD <- tidytext::unnest_tokens(tss,cleaned_text,to_lower = FALSE)
  tssBYWORD <- cbind(Uni_ID_Word = rownames(tssBYWORD),tssBYWORD)
  rownames(tssBYWORD) <- NULL
  return(tssBYWORD)
  }) -> tssBYWORD

所以这将它分成两个类为 'by' 的列表。然后我需要能够使用此函数遍历两个列表中的元素:

by(tssBYWORD,tssBYWORD$Uni_ID_Word,function(x) {
  bscore <- score.sentiment(x$cleaned_text,pos.words,neg.words,.progress='text')
  score <- as.integer(bscore$score[[1]])
  return(score)
  }) -> resultBYWORD

指的是这个函数:

# Sentiment function

score.sentiment <- function(sentences,.progress='none'){
  require(plyr)
  require(stringr)
  scores <- laply(sentences,function(sentence,neg.words){
    word.list <- str_split(sentences,'\\s+')
    words <- unlist(word.list)
    pos.matches <- match(words,pos.words)
    neg.matches <- match(words,neg.words)
    pos.matches <- !is.na(pos.matches)
    neg.matches <- !is.na(neg.matches)
    score <- sum(pos.matches) - sum(neg.matches)
    return(score)
    },.progress =.progress)
  scores.df <- data.frame(score=scores,text=sentences)
  return(scores.df)
}

我想合并前两个函数。第二个函数将不起作用,因为 'by' 不会强制。我试图通过使它成为一个数据框来让它工作,但是唯一的值不再是唯一的。我试过把它变成一个列表,但它不起作用。

请帮忙!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)