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)
print(paste("most frequently occurring: (", names(tbl)[1], ", ", tbl[[1]], ")"))
print(paste("second most frequently occurring: (", names(tbl)[2], ", ", tbl[[2]],
")"))
}
most_repeated_character(a)
I just want to get the most repeated letters, not characters. So for example if I input "Hello world &&&&", I will get 'l' as the most repeated, not '&'.
CodePudding user response:
Use the regular expression for non-alphabet characters.
The regular expression for non-alphabet characters would be [^a-zA-Z]
.
Try changing:
a <- gsub("\\s ", "", a)
to:
a <- gsub("[^a-zA-Z]", "", a)
CodePudding user response:
Another possible error that you could have is, when you enter uppercase and/or lowercase words, then, first you have to standardize the inputs, using the functions as: tolower()
or toupper()
.
librabry(tidyverse)
a <- "HolA MaMA &&&& $$$$ %%%%"
most_repeated_character <- function(x) {
x <- gsub("[^a-zA-Z]", "", x) %>%
tolower() %>%
strsplit("") %>%
table() %>%
sort(decreasing = TRUE)
print(paste("most frequently occurring: (", names(x)[1], ", ", x[[1]], ")"))
print(paste("second most frequently occurring: (", names(x)[2], ", ", x[[2]], ")"))
}
most_repeated_character(a)