[R] inefficient ifelse() ?

ivo welch ivo.welch at gmail.com
Tue Mar 1 21:36:12 CET 2011


thanks, Henrique.  did you mean

    as.vector(t(mapply(function(x, f)f(x), split(t, ((t %% 2)==0)),
list(f, g))))   ?

otherwise, you get a matrix.

its a good solution, but unfortunately I don't think this can be used
to redefine ifelse(cond,ift,iff) in a way that is transparent.  the
ift and iff functions will always be evaluated before the function
call happens, even with lazy evaluation.  :-(

I still think that it makes sense to have a smarter vectorized %if% in
a vectorized language like R.  just my 5 cents.

/iaw

----
Ivo Welch (ivo.welch at brown.edu, ivo.welch at gmail.com)





On Tue, Mar 1, 2011 at 2:33 PM, Henrique Dallazuanna <wwwhsd at gmail.com> wrote:
> Try this:
>
> mapply(function(x, f)f(x), split(t, t %% 2), list(g, f))
>
> On Tue, Mar 1, 2011 at 4:19 PM, ivo welch <ivowel at gmail.com> wrote:
>>
>> dear R experts---
>>
>>  t <- 1:30
>>  f <- function(t) { cat("f for", t, "\n"); return(2*t) }
>>  g <- function(t) { cat("g for", t, "\n"); return(3*t) }
>>  s <- ifelse( t%%2==0, g(t), f(t))
>>
>> shows that the ifelse function actually evaluates both f() and g() for
>> all values first, and presumably then just picks left or right results
>> based on t%%2.  uggh... wouldn't it make more sense to evaluate only
>> the relevant parts of each vector and then reassemble them?
>>
>> /iaw
>> ----
>> Ivo Welch
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>
>
>
> --
> Henrique Dallazuanna
> Curitiba-Paraná-Brasil
> 25° 25' 40" S 49° 16' 22" O
>



More information about the R-help mailing list