Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace first occurrence of ":" but not second in R

Tags:

regex

r

lapply

gsub

In order to be able to process I'd like to replace the first occurrence of a : in a string (which is my marker, that a speech begins).

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.")

I am able to find the position of the first : using

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

[[1]]
[1] 35

[[2]]
[1] -1

[[3]]
[1] 15

However, I am unable to replace it in text (say, for example, with a |).

like image 278
Thomas Avatar asked Dec 14 '15 14:12

Thomas


2 Answers

We can use sub as it matches only the first occurrence of pattern : and then we replace that with |.

sub(':', '|', text)
like image 85
akrun Avatar answered Sep 25 '22 05:09

akrun


You can also use str_replace from stringr package.

text1 <- c("ABC:DEF:", "SDF", "::ASW")
library(stringr)
str_replace(text1, ":", "|")
# [1] "ABC|DEF:" "SDF"      "|:ASW"  

This replaces the first occurence of : with |.

like image 28
Ronak Shah Avatar answered Sep 23 '22 05:09

Ronak Shah