在 R 中替换第一个冒号但不替换第二个冒号。

15
为了能够处理,我想要替换字符串中第一次出现的 : (这是我的标记,表示演讲开始) 。
text <- c("Mr. Mark Francois (Rayleigh) (Con): If the scheme was so poorly targeted, why were the Government about to roll it out to employees in the Department of Trade and Industry and the Department for Work and Pensions on the very day the Treasury scrapped it? The CBI and the TUC have endorsed the scheme, which has helped 500,000 people and their families to improve their computer skills. When the Chancellor announced the original concession, he told the  Daily Record:", "Even at this eleventh hour, will the Government recognise that this is a poor decision, taken by an analogue Chancellor who is stuck in the past and reversing?", "Dawn Primarolo: The hon. Gentleman answers his own question, as the US does not have similar schemes. He is right to address the question of how we give people in the greatest need access to computer technology, but the Low Pay Commission\u0092s 2005 report showed that that was not happening under the scheme. Why should the Government spend £200 million on a poorly targeted scheme? It was being abused and was not delivering, so the Government have refocused to ensure that the objective is achieved.")

我可以使用

:

来找到第一个位置。

lapply(gregexpr("\\:", text), head, 1)

[[1]]
[1] 35

[[2]]
[1] -1

[[3]]
[1] 15

然而,我无法在文本中替换它(例如,用|替换)。

2个回答

26

我们可以使用sub函数,因为它仅匹配模式中的第一次出现:,然后我们用|来替换它。

sub(':', '|', text)

2
@Thomas,sub 只会替换第一个 : 的出现。我想这就是你在问题中所询问的。 - akrun
2
这正是sub()gsub()之间的区别。 - RHertel

3
您也可以使用stringr包中的str_replace函数来进行替换操作。
text1 <- c("ABC:DEF:", "SDF", "::ASW")
library(stringr)
str_replace(text1, ":", "|")
# [1] "ABC|DEF:" "SDF"      "|:ASW"  

这将用|替换第一个出现的:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接