[R] THX-- How to use 'switch' with strings containing spaces?

Daniel Nordlund djnordlund at frontier.com
Wed Aug 24 17:31:50 CEST 2011



> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org]
> On Behalf Of Mauricio Cornejo
> Sent: Wednesday, August 24, 2011 7:53 AM
> To: Richard M. Heiberger
> Cc: r-help at r-project.org
> Subject: [R] THX-- How to use 'switch' with strings containing spaces?
> 
> Richard,
> 
> Thanks for your observation and tip.
> 
> My apologies that the 'expr' seemed undefined.  That was intentional on my
> part as I only wanted to show the form of the non-working code.  Let me be
> clearer by updating the code with what I actually type at the command
> line.  The code below does not work (error message included).
> 
> 
> x <- c("Choice 1", "Choice 2", "Choice 3")
> switch("Choice 2", x[1]="My first choice", x[2]="My 2nd choice", x[3]="My
> 3rd choice")
> Error: unexpected '=' in "switch("Choice 2", x[1]="
> 
> On an earlier reply, David Winsemius suggested using the 'match' function
> instead.  Perhaps that is the way to go, bypassing 'switch' altogether.
> But I would like to know why the code above does not work.
> 
> 
> Again, many thanks,
> Mauricio
> 
> 

Mauricio,

I haven't seen how you are trying to use this construction, or what you want the result to look like, so I am only guessing.  But does something like the following get you closer to what you want?

x <- c("Choice 1", "Choice 2", "Choice 3")
switch(x[2], 'Choice 1'="My first choice", 'Choice 2'="My 2nd choice", 'Choice 3'="My 3rd choice")

Hope this is helpful,

Dan

Daniel Nordlund
Bothell, WA USA



More information about the R-help mailing list