删除重复的字母/字母

时间:2015-05-29 19:14:08

标签: r data-manipulation

输入:kdff455556tfkkkw

输出1:kdf [2] 45 [4] 6tfk [3] w

提示:重复" alphnum"由alphnum [No_Of_Repetition]

2 个答案:

答案 0 :(得分:3)

s <- c('kdff455556tfkkkw','abc','abbccc');
sapply(strsplit(s,''),function(x) paste(with(rle(x),ifelse(lengths==1,values,paste0(values,'[',lengths,']'))),collapse=''));
## [1] "kdf[2]45[4]6tfk[3]w" "abc"                 "ab[2]c[3]"

答案 1 :(得分:1)

这是一个迂回的正则表达式方法:

require(stringr)
p <- "(([a-z0-9])\\2+)"
x <- str_split(s,p)
r <- sapply(str_extract_all(s,p),
       function(x)if (length(x))paste0(substr(x,1,1),"[",nchar(x),"]")else "")

mapply(function(x,r)paste0(
  c(x,r)[order(c(seq_along(x),seq_along(r)))]
,collapse=""),x,r)
# output for @bgoldst's input:
# [1] "kdf[2]45[4]6tfk[3]w" "abc"                 "ab[2]c[3]"

最后一步是交错技巧copied from @Arun

我希望我最初的猜测有效:

sapply(s,function(x)gsub(p,paste0("\\2[",nchar("\\1"),"]"),x))

但似乎"\\1"未在gsub内进行评估,并且总是有两个字符:

#      kdff455556tfkkkw                   abc                abbccc 
# "kdf[2]45[2]6tfk[2]w"                 "abc"           "ab[2]c[2]"