Making a nested loop using by function?

Tweets data frame is a list of tweets with keywords being from different companies ("Name"). I wanted to split these up so I put it into a loop. Works okay.

by(tweets, tweets$Name, 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)
  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,cleaned_text, to_lower = FALSE)
  tssBYWORD <- cbind(Uni_ID_Word = rownames(tssBYWORD), tssBYWORD)
  rownames(tssBYWORD) <- NULL
  return(tssBYWORD)
}) -> tssBYWORD

However, for each of these new lists I want to created a new data frame resultBYWORD which refers to a third function. It comes out with a sentiment match for each word.

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

How do I combine these two together so that they both work? A loop within a loop? I've tried just putting the second loop in and it doesn't work. They work without the other, but once I do the first one the second one no longer works. The error I am getting is that I cannot coerce a 'by' function. The class of tssBYWORD is by.

I'm not sure how to make a reproducible example as of yet but if it's difficult to answer without it then I'm sure I can come up with something.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.