[R] if() command

Sundar Dorai-Raj sundar.dorai-raj at pdf.com
Tue Sep 13 15:41:23 CEST 2005



Carlos Maurício Cardeal Mendes wrote:
> Hi everyone !
> 
> Could you please help me with this problem ?
> 
> I´ve trying to write a code that assign to a variable the content from 
> another, but all I´ve got is a message error. For example:
> 
> if (age <=10) {group == 1}
> else if (age > 10 & age <= 20) {group == 2}
> else {group == 3}
> 
> Syntax error
> 
> Or
> 
> if (age <=10) {group == 1}
> else (age > 10 & age <= 20) {group == 2}
> else {group == 3}
> 
> Syntax error
> 
> I know that is possible to find the solution by ifelse command or even 
> recode command, but I´d like to use this way, because I can add another 
> variable as a new condition and I believe to expand the possibilites.
> 
> Thanks,
> Mauricio
> 

Because the following line is syntatically correct:

if (age <=10) {group == 1}

the R parser does not expect the following:

else (age > 10 & age <= 20) {group == 2}
else {group == 3}

causing a sytax error. Instead, you want:

if (age <=10) {
   group == 1
} else (age > 10 & age <= 20) {
   group == 2
} else {
   group == 3
}

HTH,

--sundar




More information about the R-help mailing list