[R] ifelse(logical, function1, function2) does not work

Thomas Lumley tlumley at u.washington.edu
Mon Oct 9 16:55:03 CEST 2006


On Sat, 7 Oct 2006, Rolf Turner wrote:

> Peter Dalgaard writes:
>
>> Alberto Vieira Ferreira Monteiro <albmont at centroin.com.br> writes:
>>
>>> Why this kind of assignment does not work?
>>>
>>>   n <- 1
>>>   f <- ifelse(n == 1, sin, cos)
>>>   f(pi)
>>
>> It's not supposed to.
>>
>>      'ifelse' returns a value with the same shape as 'test' which is
>>      filled with elements selected from either 'yes' or 'no' depending
>>      on whether the element of 'test' is 'TRUE' or 'FALSE'.
>>
>> which makes very little sense if yes and no are functions.
>
> 	I think that's a debatable assertion.  Why might I
> 	not want a vector, or rather a list, of functions?
>

You might want a list of functions, but in that case ifelse() would have 
to return a list of functions, and in the example in question it would 
return list(sin) rather than sin.

There is a real difference between lists of functions and the things that 
rep() works on, in that a vector of one number is the same as that number, 
but a list of one function is not the same as the function.

 	-thomas

Thomas Lumley			Assoc. Professor, Biostatistics
tlumley at u.washington.edu	University of Washington, Seattle



More information about the R-help mailing list