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

Peter Dalgaard p.dalgaard at biostat.ku.dk
Sat Oct 7 15:01:47 CEST 2006


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.
 
> this must be rewritten as:
> 
>   n <- 1
>   f <- cos
>   if (n == 1) f <- sin
>   f(pi)

No, it must not.

n <- 1
f <- if (n==1) sin else cos
f(pi)

or even 

(if (n==1) sin else cos)(pi)

-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907



More information about the R-help mailing list