[R] Manipulate strings reordering some elements

Berend Hasselman bhh at xs4all.nl
Tue Mar 13 11:51:49 CET 2012


On 13-03-2012, at 11:28, Igor Sosa Mayor wrote:

> many thanks, Berend.
> 
> It works well... but with a problem because i was not completely clear
> in my first email.
> 
> It works with cases such as:
> Franco (El)
> Regueras (Las)
> 
> but not with other cases such as:
> Fauces de San Andrés (Las)
> 
> any hints? or meaybe if it is very complicated, any short explanation of
> the perl expression you wrote (as far as I can understand, the point is
> this \\3 \\1...).


Try this

gsub("([^\\(]+)(\\()(.*)(\\))","\\3 \\1", municipios, perl=TRUE)

([^\\(]+)   look for a sequence of characters not (, this becomes the \1

(\\()         match (

(.*)          match zero or more anything, this becomes \3

(\\))        match closing )

All subexpressions surrounded by ()  for backreferencing in replacement expression to work.

The result of the above expression will contain trailing blanks if there was a (El) etc.
You can get rid of those by using gsub("\\s+$","",x)

I'm in a bit of a hurry now, so I won't be able to answer further questions for several hours.

Berend



More information about the R-help mailing list