Home > Back-end >  How to return two of the most repeating character from user text
How to return two of the most repeating character from user text

Time:11-21

a <- as.character(readline(" Please input a text:    "))
most_repeated_character <- function(x) {
  a <- gsub("\\s ", "", a)
  lets <- strsplit(a, "")[[1]]
  tbl <- sort(table(lets), decreasing=TRUE)
  paste("most frequently occurring: (", names(tbl)[1], ", ", tbl[[1]], ")")
  paste("second most frequently occurring: (", names(tbl)[2], ", ", tbl[[2]], ")")
}
print(most_repeated_character(a))

Im facing a problem when I want to get the output, it only shows the second most frequent character, and it's not showing the first one.

CodePudding user response:

Only the last value evaluated is returned. To return both, put them in a character vector:

most_repeated_character <- function(x) {
  a <- gsub("\\s ", "", a)
  lets <- strsplit(a, "")[[1]]
  tbl <- sort(table(lets), decreasing=TRUE)
  c(paste("most frequently occurring: (", names(tbl)[1], ", ", tbl[[1]], ")"),
  paste("second most frequently occurring: (", names(tbl)[2], ", ", tbl[[2]], ")"))
}

a <- "The quick brown fox jumped over the lazy dog."
most_repeated_character(a)
[1] "most frequently occurring: ( e ,  4 )"       
[2] "second most frequently occurring: ( o ,  4 )"

Note, use paste0() if you don’t want the space separators.

CodePudding user response:

@zephryl answer pointed your error and works great, but you might want to change the function into one that only prints the info:

most_repeated_character <- function(x) {
  a <- gsub("\\s ", "", a)
  lets <- strsplit(a, "")[[1]]
  tbl <- sort(table(lets), decreasing=TRUE)
  cat(paste("most frequently occurring: (", names(tbl)[1], ", ", tbl[[1]], ")"))
  cat(paste("\nsecond most frequently occurring: (", names(tbl)[2], ", ", tbl[[2]], ")"))
}

Result:

> most_repeated_character(a)
most frequently occurring: ( a ,  5 )
second most frequently occurring: ( s ,  5 )

Obs: you can change the cat function into print.

  •  Tags:  
  • r
  • Related