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

如何在R语言中对包含指定字符串的列值进行重编码?

R语言:将包含特定字符串的列值重编码为指定内容

你的原始数据集:

df <- data.frame(id = c(1,2,3,4,5),
                 text = c("John S", "John P", "John","Steve","Sam"))

需求:将text列中所有包含John的值统一替换为John,其余值保持不变。

方法一:Base R 原生实现

使用grepl检测字符串是否包含目标模式,配合ifelse完成替换:

df$text <- ifelse(grepl("John", df$text), "John", df$text)
# 查看结果
df

方法二:tidyverse 工具链实现

如果习惯使用管道式数据处理,可以用dplyr结合stringr包:

library(tidyverse)

# 方式1:用ifelse
df1 <- df %>%
  mutate(text = ifelse(str_detect(text, "John"), "John", text))

# 方式2:用case_when(更适合多条件场景,可读性更强)
df1 <- df %>%
  mutate(text = case_when(
    str_detect(text, "John") ~ "John",
    TRUE ~ text  # 其他情况保留原内容
  ))

# 查看结果
df1

两种方法最终都会得到你期望的输出:

> df1
  id  text
1  1  John
2  2  John
3  3  John
4  4 Steve
5  5   Sam

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 14:45:33