You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R语言中如何将含3个及以上重复字母的单词替换为NA?

Replace Words with 3+ Consecutive Identical Letters to NA in R

Got it, let's solve this problem where we need to swap any word with three or more consecutive identical characters for NA in R. Whether you're cleaning messy text data or standardizing inputs, here are straightforward ways to get this done:

Sample Data First

Let's start with some example words to test our code:

# Test vector of words
words <- c("apple", "cakkkkkkkkkkkkkkkeeeeeee", "banana", "zzzzzzzzz", "hello", "aaabbb")

Base R Approach (No Additional Packages)

If you don't want to load extra libraries, use base R's grepl() to identify matches and replace them directly:

# Flag words with 3+ consecutive repeats and set to NA
words[grepl("(.)\\1{2,}", words)] <- NA

# Check the result
words
# Output: "apple" NA      "banana" NA      "hello"  NA

Tidyverse/stringr Approach

If you're already using the tidyverse, stringr makes this even more readable with str_detect() and if_else():

library(stringr)

# Replace matches with NA, keep others as-is
words_clean <- if_else(str_detect(words, "(.)\\1{2,}"), NA_character_, words)

words_clean
# Same output as above!

Breaking Down the Regex

The magic here is the regular expression (.)\\1{2,}:

  • (.): Captures any single character (this is our "target" letter)
  • \\1: References the character we just captured (so we're looking for the same letter again)
  • {2,}: Requires that the referenced character repeats at least 2 times—combined with the initial capture, that's 3+ consecutive identical letters total.

This regex will catch all cases like zzzzzzzzz (9 z's) or cakkkkk...eeeeee (multiple runs of repeated letters in one word).

内容的提问来源于stack exchange,提问作者Praveen Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:27:15