Skip to content

ifelse()

3 messages · kayj, David Winsemius, Philipp Pagel

#
I have a problem with ifelse(), I do not understand how it works.
num [1:6] 2 2 1 1 0 0
[1] 1 1 1 1 0 0
Can some one explain what is going on, I do not understand what ifelse is
doing in this case. Can someone explain the output Y.

Thanks
#
It is checking the series of values of X and returning a series of 1  
and 0's;
    1 if it meets your condition (X>0) and
    0 if it doesn't.

What did you expect?

A more complex invocation might look like this:
 > ifelse( X > 0, 1:3, -1:-2)
[1]  1  2  3  1 -1 -2
Note the recycling of the elements of the yes and no arguments

Consider also:

 > (X>0)+0
[1] 1 1 1 1 0 0
#
On Tue, Feb 10, 2009 at 01:44:17PM -0800, kayj wrote:
ifelse evaluates the condition given in its first argument and returns
the value of the second argument for all cases found to be TRUE and
the value of the third argument otherwise. As the first 4 elments of X
fulfill your condition (X>0) the corresponding result for them is 1 and
the rest 0.

See ?ifelse for details.

cu
	Philipp