如何解决需要嵌套循环或其他方式在 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 举报,一经查实,本站将立刻删除。