通过删除连续的重复项来减少字符串长度

Joe*_*Joe 4 string r dataframe dimensionality-reduction

我有一个R数据框,有两个字段:

ID             WORD
1           AAAAABBBBB
2           ABCAAABBBDDD
3           ...
Run Code Online (Sandbox Code Playgroud)

我想通过重复字母简化字母,而不是重复字母而不是重复字母:

例如:AAAAABBBBB应该给我AB 并且 ABCAAABBBDDD应该给我ABCABD

任何人都知道如何做到这一点?

Blu*_*ter 8

这是一个正则表达式的解决方案:

x <- c('AAAAABBBBB', 'ABCAAABBBDDD')
gsub("([A-Za-z])\\1+","\\1",x)
Run Code Online (Sandbox Code Playgroud)

编辑:根据要求,一些基准测试.我在评论中添加了Matthew Lundberg的模式,匹配任何角色.它似乎gsub更快一个数量级,匹配任何字符比匹配字母更快.

library(microbenchmark)
set.seed(1)
##create sample dataset
x <- apply(
  replicate(100,sample(c(LETTERS[1:3],""),10,replace=TRUE))
,2,paste0,collapse="")
##benchmark
xm <- microbenchmark(
    SAPPLY = sapply(strsplit(x, ''), function(x) paste0(rle(x)$values, collapse=''))
    ,GSUB.LETTER = gsub("([A-Za-z])\\1+","\\1",x)
    ,GSUB.ANY = gsub("(.)\\1+","\\1",x)
)
##print results
print(xm)
# Unit: milliseconds
         # expr       min        lq    median        uq       max
# 1    GSUB.ANY  1.433873  1.509215  1.562193  1.664664  3.324195
# 2 GSUB.LETTER  1.940916  2.059521  2.108831  2.227435  3.118152
# 3      SAPPLY 64.786782 67.519976 68.929285 71.164052 77.261952

##boxplot of times
boxplot(xm)
##plot with ggplot2
library(ggplot2)
qplot(y=time, data=xm, colour=expr) + scale_y_log10()
Run Code Online (Sandbox Code Playgroud)