我有以下名字,我正在尝试将其更改为名字、姓氏格式。
myNamesDup
"Cross K / Cross M" "Davis L/Harper C" "Williams M /
Brown M G" "Greening E-L / Roberts J" "Jones Williams D/Browning A"
What I am trying to achieve;
"K Cross/M Cross" "L Davis/C Harper" "M Williams/M G
Brown " "E-L Greening/j Roberts" "A Jones Williams/A Browning"
我为此尝试了一些方法但不成功,主要是因为我认为是特殊字符。
The closest I got to this is by using;
gsub("([A-Za-z]*) (.*)/(.*) ([A-Za-z]*)", "\\2 \\1/\\4 \\3", myNamesDup)
这让我非常接近,似乎在双桶名称和 2 个首字母缩写上失败了
您可以尝试使用
strsplit
和 sub
,如下所示
> unlist(lapply(strsplit(myNames, "/"), \(x) paste0(sub("(\\S+) (.*)", "\\2 \\1", trimws(x)), collapse = "/")))
[1] "K Cross/M Cross" "L Davis/C Harper"
[3] "M Williams/M G Brown" "E-L Greening/J Roberts"
[5] "Williams D Jones/A Browning"