Use of [:alnum:] or . in gsub() etc..

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Use of [:alnum:] or . in gsub() etc..

ppaarrkk

test = c ( "AAABBB", "CCC" )


This works :

gsub ( "[A-Z]", "2", test )



None of these do :

gsub ( "[A-Z]", [:alnum:], test )
gsub ( "[A-Z]", [[:alnum:]], test )
gsub ( "[A-Z]", "[:alnum:]", test )
gsub ( "[A-Z]", "[[:alnum:]]", test )
gsub ( "[A-Z]", "^[:alnum:]$", test )



What am I doing wrong, please ?
Reply | Threaded
Open this post in threaded view
|

Re: Use of [:alnum:] or . in gsub() etc..

Marc Schwartz
on 01/16/2009 10:13 AM ppaarrkk wrote:

>
> test = c ( "AAABBB", "CCC" )
>
>
> This works :
>
> gsub ( "[A-Z]", "2", test )
>
>
>
> None of these do :
>
> gsub ( "[A-Z]", [:alnum:], test )
> gsub ( "[A-Z]", [[:alnum:]], test )
> gsub ( "[A-Z]", "[:alnum:]", test )
> gsub ( "[A-Z]", "[[:alnum:]]", test )
> gsub ( "[A-Z]", "^[:alnum:]$", test )
>
>
>
> What am I doing wrong, please ?

The syntax ordering is off. You are in effect trying to replace the
characters A-Z with the character vector "[[:alnum:]]". Thus:

> gsub ("[A-Z]", "[[:alnum:]]",  test )
[1] "[[:alnum:]][[:alnum:]][[:alnum:]][[:alnum:]][[:alnum:]][[:alnum:]]"
[2] "[[:alnum:]][[:alnum:]][[:alnum:]]"


Recall the basic syntax for gsub() is:

  gsub(SearchPattern, ReplacementVector, Source)


What you want is:

> gsub ("[[:alnum:]]", "2" , test )
[1] "222222" "222"


HTH,

Marc Schwartz

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.