Skip to content

if() command

7 messages · vincent@7d4.com, PIKAL Petr, Carlos Mauricio Cardeal Mendes +2 more

#
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
#
Carlos Maur??cio Cardeal Mendes wrote:
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
1 day later
#
Ok Petr, I run your suggestion and I got this message:

 > age<-sample(seq(10,50,10), 20, replace=T)
 >
 > if (age <=10) {group <- 1} else if (age > 10 & age <= 20) {group <- 
2} else {group <- 3}
Warning message:
the condition has length > 1 and only the first element will be used in: 
if (age <= 10) {

What does it means ?

And when I look to the database I have no new classification !

Could you help please ?

Mauricio

Petr Pikal escreveu:
#
"if" is not vectorised and "age" is a vector. Try the following test:

if(c(TRUE, FALSE)) "TRUE" else "FALSE"

You really need to use "ifelse".

ifelse(c(TRUE, FALSE), "TRUE", "FALSE")

As others have suggested, you might want to look at ?cut.

--sundar
Carlos Mauricio Cardeal Mendes wrote:
#
On Wed, 14 Sep 2005, Carlos Mauricio Cardeal Mendes wrote:

            
Although the syntax issue is real, if() is not the way to go if you are 
comparing a vector with a scalar; if() will only compare the first element 
of the vector with the scalar. The ifelse() function is vectorised:
[1] 3 2 3 3 3 2 3 3 1 2 3 1 1 1 3 2 3 2 3 3

or maybe even better, use the cut function to create a grouping factor:
[1] (20,100] (10,20]  (20,100] (20,100] (20,100] (10,20]  (20,100] (20,100]
 [9] [0,10]   (10,20]  (20,100] [0,10]   [0,10]   [0,10]   (20,100] (10,20] 
[17] (20,100] (10,20]  (20,100] (20,100]
Levels: [0,10] (10,20] (20,100]
[1] 30 20 30 40 30 20 50 50 10 20 30 10 10 10 30 20 40 20 50 40
[1] 3 2 3 3 3 2 3 3 1 2 3 1 1 1 3 2 3 2 3 3

Sometimes you need to enclose cut() within ordered(), and if there are 
empty intervals, you may not get what you expect from the integer 
representation of the result. Yet another elegant function is 
findInterval():
[1] 3 2 3 3 3 2 3 3 1 2 3 1 1 1 3 2 3 2 3 3

Hope this helps