Skip to content
Prev 77210 / 398502 Next

if() command

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