Reputation:
Find most common digit in a string. Using stringr
output : 3 or '3'
EX: common(I am 29. Born in 1990)
Upvotes: 0
Views: 73
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