[R] replace text at certain positions in a file

Gabor Grothendieck ggrothendieck at gmail.com
Tue Nov 2 13:23:36 CET 2010


On Tue, Nov 2, 2010 at 6:20 AM, RINNER Heinrich
<HEINRICH.RINNER at tirol.gv.at> wrote:
> Hello,
>
> thanks again for this nice solution using sub and regular expressions!
> However, in real life I have to overwrite more than two positions with blanks (say 50 or so), so I was trying to modify this in the following way:
>
>> s <- c("ab34cd78e", "fg3 hi78j")
>
> # your suggestion (works perfectly for the simple case):
>> sub("^(..)..(..)..", "\\1  \\2  ", s)
> [1] "ab  cd  e" "fg  hi  j"
>
> # gereralizing the pattern (works as well):
>> sub("^(.{2}).{2}(.{2}).{2}", "\\1  \\2  ", s)
> [1] "ab  cd  e" "fg  hi  j"
>
> # generalizing the replacement (doesn't work):
>>  sub("^(.{2}).{2}(.{2}).{2}", "\\1 {2}\\2 {2}", s)
> [1] "ab {2}cd {2}e" "fg {2}hi {2}j"
>
> Apparently, " {2}" ist not interpreted as a string with two blanks ("  ") in the replacement part, so something is wrong in my expression there. I just can't figure out what...
>

If its always the same pattern repeated over and over then this works:

   gsub("(..)..", "\\1  ", s)

-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list