How to extract repeated characters in R

Viewed 282

I'm trying to extract those phonemes that reoccur in words. I've phonemic transcriptions of words such as these:

x <- c("saɪəns", "ɪvɒlvd", "ˌʌndəstænd", "skɑːb(ə)rə", "pəteɪtəʊ", "dɪskraɪbd")

Using gsub and backreference, I can do this:

gsub(".*(.).*\\1.*", "\\1", x, perl = T)
[1] "s" "v" "d" "ə" "t" "ɪ"

However the result is incomplete, as only one repeated letter is outputted; the complete result would be:

[1] "s" "v" "nd" "ə" "ət" "dɪ"

I've tried it with multiple backreference but this outputs the entire strings:

gsub(".*(.).*\\1.*(.).*\\2", "\\1\\2", x, perl = TRUE)
[1] "saɪəns"     "ɪvɒlvd"     "ˌʌndəstænd" "skɑːb(ə)rə" "pəteɪtəʊ"   "dɪskraɪbd"

Can anybody help?

2 Answers

You can use

library(stringr)
x <- c("saɪəns", "ɪvɒlvd", "ˌʌndəstænd", "skɑːb(ə)rə", "pəteɪtəʊ", "dɪskraɪbdɪ")
sapply(str_extract_all(x, "(.)(?=.*\\1)"), function(z) paste(unique(z), collapse=""))
# => [1] "s"  "v"  "nd" "ə"  "ət" "dɪ"

See an online R demo.

The (.)(?=.*\1) regex finds all chars that are followed with any zero or more chars other than line break chars, as many as possible, until the same char. The stringr::str_extract_all extracts all occurrences (so the total amount of the same char is n-1). Since this results in duplicates, the uniq function must be applied to each character vector when collapseing.

tabulate letter frequency and return those appearing more than once?

sapply(strsplit(x, ''), function(s){ f <- table(s); paste0(names(f[f>1]), collapse = '') })
# [1] "s"  "v"  "dn" "ə"  "ət" "dɪ"

An empty string will be returned in case of no repeated characters:

x <- c('abb', 'ab')
sapply(strsplit(x, ''), function(s){ f <- table(s); paste0(names(f[f>1]), collapse = '') })
# [1] "b" "" 
Related