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

如何统一DataFrame中姓名格式:将「名 姓」转为「姓, 名」

统一姓名格式为「姓, 名」的解决方案

可以用tidyverse工具包中的dplyr和stringr实现直接在原DataFrame中修改Names列,具体步骤如下:

1. 构造示例数据

先还原你的示例数据集:

library(tidyverse)

df <- tibble(
  Names = c("Smith, John", "Sam Miller", "Anderson, Sam", "Williams, Jacob", "Susan Styles", "Burke, David"),
  Other_Column = rep("...", 6)
)

2. 统一姓名格式

通过管道操作+条件判断,直接修改原列:

df <- df %>%
  mutate(Names = case_when(
    # 已为「姓, 名」格式的,直接保留
    str_detect(Names, ",") ~ Names,
    # 「名 姓」格式的,分割后反转拼接
    TRUE ~ str_split_fixed(Names, " ", 2) %>% 
      as_tibble() %>% 
      mutate(full_name = paste0(V2, ", ", V1)) %>% 
      pull(full_name)
  ))

也可以用更简洁的写法,避免嵌套tibble:

df <- df %>%
  mutate(
    Names = ifelse(
      str_detect(Names, ","),
      Names,
      paste(str_split(Names, " ", simplify = TRUE)[,2], str_split(Names, " ", simplify = TRUE)[,1], sep = ", ")
    )
  )

3. 验证结果

处理后Names列会全部统一为「姓, 名」格式:

print(df$Names)
# 输出:
# [1] "Smith, John"    "Miller, Sam"    "Anderson, Sam"  "Williams, Jacob" "Styles, Susan"  "Burke, David"

关键函数说明

  • str_detect(Names, ","):检测姓名中是否包含逗号,判断当前格式是否正确
  • str_split_fixed(Names, " ", 2):将「名 姓」格式的字符串按空格分割为两部分,分别对应名和姓
  • paste0(V2, ", ", V1):将分割后的姓(V2)和名(V1)拼接为「姓, 名」格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 03:05:41