[R] switch() usage

Nordlund, Dan (DSHS/RDA) NordlDJ at dshs.wa.gov
Wed Aug 27 03:09:46 CEST 2008


> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Michael A. 
> Gilchrist
> Sent: Tuesday, August 26, 2008 6:03 PM
> To: r-help at r-project.org
> Subject: [R] switch() usage
> 
> Hello,
> 
> I am wondering if it is possible to run separate lines of 
> code within switch() 
> as one can do in most languages.
> 
> For example, I'd like to have switch execute a few lines of 
> code based on the 
> value passed to it.
> 
> For example,
> 
> >index = 1
> >
> >switch(index,
> >	command 1; command 2; command 3, #execute if index = 1
> >	command 4; command 5; command 6, #execute if index = 2
> >	command 7....                    #execute if index = 3
> >
> >)
> 
> However, if I try this syntax, I get an error about an 
> unexpected ';'. I've 
> tried wrapping the commands in () but that doesn't help either.
> 
> Is there a way to do this without having to  write separate 
> functions for each 
> of the switch possibilities.
> 
> Thanks.
> 
> 
> Mike
> 
> 
Mike,

Did you try wrapping the series of commands in braces {}:

switch(index,
	{command 1; command 2; command 3}, #execute if index = 1
	{command 4; command 5; command 6}, #execute if index = 2
	{command 7....   }                 #execute if index = 3
)

Hope this is helpful,

Dan

Daniel J. Nordlund
Washington State Department of Social and Health Services
Planning, Performance, and Accountability
Research and Data Analysis Division
Olympia, WA  98504-5204
 
 



More information about the R-help mailing list