更改单词在 r 中的字符串中的位置 [英] change position of word within a string in r
本文介绍了更改单词在 r 中的字符串中的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串向量,看起来像:
I have a string vector that looks like:
> string_vec
[1] "XXX" "Snakes On A Plane" "Mask of the Ninja" "Ruslan"
[5] "Kill Switch" "Buddy Holly Story, The" "Believers, The" "Closet, The"
[9] "Eyes of Tammy Faye, The" "Gymnast, The" "Hunger, The"
有些名称包含, The"到底.我想删除逗号和空格并移动The"在所有其他文本之前.
There are some names which contain ", The" in the end. I want to delete the comma and the space and move the "The" before all other text.
例如:Buddy Holly Story, The"变成了巴迪冬青的故事".
For e.g.: "Buddy Holly Story, The" becomes "The Buddy Holly Story".
使用模式隔离记录很容易:
Isolating the records with the pattern was easy :
string_vec[grepl("[Aa-zZ]+, The", string_vec) == TRUE]
我现在如何调整位置?
string_vec <- c("XXX", "Snakes On A Plane", "Mask of the Ninja",
"Ruslan",
"Kill Switch", "Buddy Holly Story, The", "Believers, The",
"Closet, The",
"Eyes of Tammy Faye, The", "Gymnast, The", "Hunger, The")
推荐答案
你可以试试
sub('^(.*), The', 'The \\1', string_vec)
#[1] "XXX" "Snakes On A Plane" "Mask of the Ninja"
#[4] "Ruslan" "Kill Switch" "The Buddy Holly Story"
#[7] "The Believers" "The Closet" "The Eyes of Tammy Faye"
#[10] "The Gymnast" "The Hunger"
这篇关于更改单词在 r 中的字符串中的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文