user13413688
user13413688

Reputation:

In r, extracting the most common digit in a string

Find most common digit in a string. Using stringr

Upvotes: 0

Views: 73

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389135

We can create a function, remove all non-digits, split and return the number with maximum count.

common <- function(x) {
   names(which.max(table(strsplit(gsub('\\D', '', x), "")[[1]])))
}

common(123333)
#[1] "3"

common('I am 29. Born in 1990')
#[1] "9"

We can also use str_extract_all here :

common <- function(x) {
  names(which.max(table(stringr::str_extract_all(x, '\\d')[[1]])))
}

Upvotes: 1

Related Questions