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

基于字符串条件交换列值的R语言dplyr解决方案

使用dplyr修正姓名列错位问题

原始数据定义

df <- read.table(text="
first_name  last_name
James   Durant
'Richard Iii'   Michael
Ben     Green
'Johnson Jr.'   Tom", header= TRUE)

需求说明

部分first_name列的字符串带有Ii或Jr.后缀,这类内容实际属于姓氏,需要在匹配到该条件时,交换first_name和last_name的取值,让姓名归入正确的列。

解决方案(基于dplyr)

需要用到dplyr进行数据变换,结合stringr的字符串匹配功能:

# 加载所需包
library(dplyr)
library(stringr)

# 修正姓名列
df_corrected <- df %>%
  mutate(
    # 临时存储原last_name值,防止交换时数据覆盖
    temp_last = last_name,
    # 匹配到条件时,把first_name赋值给last_name
    last_name = case_when(
      str_detect(first_name, "\\s(Ii|Jr\\.)$") ~ first_name,
      TRUE ~ last_name
    ),
    # 匹配到条件时,把原last_name赋值给first_name
    first_name = case_when(
      str_detect(first_name, "\\s(Ii|Jr\\.)$") ~ temp_last,
      TRUE ~ first_name
    )
  ) %>%
  select(-temp_last) # 删除临时列

# 查看修正结果
print(df_corrected)

结果说明

运行后得到的修正数据集如下:

first_name    last_name
1      James        Durant
2    Michael    Richard Iii
3        Ben         Green
4        Tom Johnson Jr.
  • 正则表达式\\s(Ii|Jr\\.)$用于精准匹配以空格加Ii或Jr.结尾的字符串,避免误匹配其他情况
  • 通过临时列temp_last中转数据,确保交换过程中不会丢失原有的姓氏信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 19:40:13