2015-12-14 20 views
5

Per poter elaborare, desidero sostituire la prima occorrenza di uno : in una stringa (che è il mio indicatore, che inizia un discorso).Sostituire la prima occorrenza di ":" ma non la seconda in R

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

sono in grado di trovare la posizione del primo : utilizzando

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

[[1]] 
[1] 35 

[[2]] 
[1] -1 

[[3]] 
[1] 15 

Tuttavia, non sono in grado di sostituirlo in text (diciamo, per esempio, con un |).

risposta

13

Possiamo usare sub perché corrisponde solo alla prima occorrenza del modello : e quindi lo sostituiamo con |.

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

@Thomas Il 'sub' sostituisce solo la prima occorrenza di': '. Immagino sia quello che hai chiesto nella domanda. – akrun

+0

questo è \t imbarazzante. grazie! – Thomas

+0

Questa è precisamente la differenza tra 'sub()' e 'gsub()'. – RHertel

2

È inoltre possibile utilizzare str_replace da stringr pacchetto.

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

Questo sostituisce la prima occorrenza di : con |.