[R] Remove all spaces from a string so it can be used by assign()

Romain Francois romain.francois at dbmail.com
Fri Jul 3 13:09:20 CEST 2009


On 07/03/2009 12:56 PM, Kurt Smith wrote:
>
> Hi
>
> I have a string "56 Fe [1]" that I would like to use as a variable name by using "assign" however I think the spaces and brackets might be causing R some trouble.

Not really;

R> assign( "56 Fe [1]", 10 )
R> `56 Fe [1]`
[1] 10

> How can I change the string so that it just becomes 56Fe1 and can be used as a variable name.

56Fe1 is not good enough to be assigned without quotes

R> 56Fe1 <- 10
Error: unexpected symbol in "56Fe1"

You might be interested in make.names

R> make.names( "56 Fe [1]" )
[1] "X56.Fe..1."

Otherwise, to answer your question, you can :

R> gsub( "[^[:alnum:]]", "", "56 Fe [1]" )
[1] "56Fe1"


> Thank You
>
> Kurt


-- 
Romain Francois
Independent R Consultant
+33(0) 6 28 91 30 30
http://romainfrancois.blog.free.fr
|- http://tr.im/qJ8V : RGG#153: stars network
|- http://tr.im/qzSl : using ImageJ from R: the RImageJ package
`- http://tr.im/qzSJ : with semantics for java objects in rJava




More information about the R-help mailing list