How to automate repetitive part for rest of groups

I am using R, to find the most repetitive word (bigram) in each group.

In the sample example there are only two groups which are (3 and 4).

However, in real I have 20 Groups. I managed to write R script for only 1 group.

How can I automate for the rest of groups ?



word.freq <- function(TDM, sortBy='fr.eq'){
  freq <- slam::row_sums(TDM)
  if (sortBy=='freq') freq <- sort(freq,decreasing=T)

BigramTokenizer <-
  function(x) unlist(lapply(ngrams(words(x), 2), paste, collapse = " "), use.names = FALSE)

AllGroups <- data.frame(
  KeyResult_Name= c("Search Optimization Engine Rank (keywords to be defined)",
                    "CRM Daily (Configuration and Database) Backups Per Year",
                    "Monthly CRM Security Access Health Check and Report",
                    "Monthly CRM Performance Health Check and Reports",
                    "Monthly CRM Security Access Health Check and Report",
                    "Participants Satisfaction Index Survey",
                    "Employees Satisfaction Index Survey",
                    "End User Satisfaction",
                    "End User Satisfaction",
                    "End User Satisfaction",
                    "Customer Satisfaction",
                    "Employee Satisfaction Index Rate"),
  Assignments= c(3,3,3,3,3,4,4,4,4,4,4,4)

onegroup1 <-AllGroups[AllGroups$Assignments == '4',]
onegroup <- Corpus(VectorSource(onegroup1$KeyResult_Name)) 
onegroup.TDM <- TermDocumentMatrix(onegroup, control = list(tokenize = BigramTokenizer))
onegroup.word.freq <- word.freq(onegroup.TDM )
onegroup.words <- names(onegroup.word.freq)

df <- data.frame(onegroup.words,onegroup.word.freq )
colnames(df) <- c("GroupName","freq")
sorter <- order(df[,2],decreasing=T)
df<- df[sorter,]
df <-head(df,1) 

total <- data.frame(df,Group)