How to get the most frequent character within a character string?

Viewed 73

Suppose the next character string:

test_string <- "A A B B C C C H I"

Is there any way to extract the most frequent value within test_string?

Something like:

extract_most_frequent_character(test_string)

Output:

#C
4 Answers

We can use scan to read the string as a vector of individual elements by splitting at the space, get the frequency count with table, return the named index that have the max count (which.count), get its name

extract_most_frequent_character <- function(x) {
     names(which.max(table(scan(text = x, what = '', quiet = TRUE))))
}

-testing

extract_most_frequent_character(test_string)
[1] "C"

Or with strsplit

extract_most_frequent_character <- function(x) {
     names(which.max(table(unlist(strsplit(x, "\\s+")))))
}

Here is another base R option (not as elegant as @akrun's answer)

> intToUtf8(names(which.max(table(utf8ToInt(gsub("\\s", "", test_string))))))
[1] "C"

One possibility involving stringr could be:

names(which.max(table(str_extract_all(test_string, "[A-Z]", simplify = TRUE))))

[1] "C"

Or marginally shorter:

names(which.max(table(str_extract_all(test_string, "[A-Z]")[[1]])))

Here is solution using stringr package, table and which:

library(stringr)
test_string <- str_split(test_string, " ")

test_string <- table(test_string)

names(test_string)[which.max(test_string)]

[1] "C"
Related