【发布时间】:2021-03-02 11:12:58
【问题描述】:
我有一个字符列,如下所示:
names <- c("Isle North East", "London Northwestern", "Bedfordshire North East", "Southwark and Bermondsey North East",
"Middlesbrough South and Cleveland East")
我想做的是将表达式 "North East" 移动到它之前出现的任何单词之前。因此,如果字符串是 XXXX XXXX North East,例如我希望它是“XXXX North East XXXX”。如果我展示我正在寻找的解决方案,也许会更容易:
ideal.names <- c("North East Isle", "London Northwestern", "North East Bedfordshire", "Southward and North East Bermondsey",
"Middlesbrough South and Cleveland East")
我尝试了不同的方法,例如:
c(sub('^(.*) North East', 'North East \\1', names))
但这会返回以下内容:
[1] "North East Isle" "London Northwestern"
[3] "North East Bedfordshire" "North East Southwark and Bermondsey"
[5] "Middlesbrough South and Cleveland East"
所以问题是这会将字符串North East 移动到字符串的开头,而不是在它之前的单词之前。所以我得到North East Southwark and Bermondsey 而不是Southward and North East Bermondsey,这就是我想要的。
任何帮助都会很棒。
谢谢!
【问题讨论】: