built-in ifelse [🇷 for BE/BA]

posted by mittyri  – Russia, 2019-04-30 15:05 (2192 d 04:00 ago) – Posting: # 20263
Views: 8,504

Hi ElMaestro,

please see ifelse internals:
function (test, yes, no)
{
  if (is.atomic(test)) {
    if (typeof(test) != "logical")
      storage.mode(test) <- "logical"
    if (length(test) == 1 && is.null(attributes(test))) {
      if (is.na(test))
        return(NA)
      else if (test) {
        if (length(yes) == 1) {
          yat <- attributes(yes)
          if (is.null(yat) || (is.function(yes) && identical(names(yat),
            "srcref")))
            return(yes)
        }
      }
      else if (length(no) == 1) {
        nat <- attributes(no)
        if (is.null(nat) || (is.function(no) && identical(names(nat),
          "srcref")))
          return(no)
      }
    }
  }
  else test <- if (isS4(test))
    methods::as(test, "logical")
  else as.logical(test)
  ans <- test
  ok <- !is.na(test)
  if (any(test[ok]))
    ans[test & ok] <- rep(yes, length.out = length(ans))[test & ok]
  if (any(!test[ok]))
    ans[!test & ok] <- rep(no, length.out = length(ans))[!test & ok]
  ans
}


That's why Hadley implemented his own if_else function. Your one if in f2 is substituted to many of in f1. And the last part is two separated actions for 'No' and 'Yes'.
So you can write your own ifelse function (for your own purposes) which will be much faster than the built-in

And the winner is
f3 = function(x, Len)
{
  rslt=rep("foo", Len)
  rslt[which(x==1, arr.ind = T)]="bar"
  return(rslt)
}

Kind regards,
Mittyri

Complete thread:

UA Flag
Activity
 Admin contact
23,424 posts in 4,927 threads, 1,667 registered users;
17 visitors (0 registered, 17 guests [including 9 identified bots]).
Forum time: 19:06 CEST (Europe/Vienna)

Garbage in, garbage out.
It’s very very simple.    Anders Fuglsang

The Bioequivalence and Bioavailability Forum is hosted by
BEBAC Ing. Helmut Schütz
HTML5