built-in ifelse [🇷 for BE/BA]

posted by mittyri – Russia, 2019-04-30 15:05 (1794 d 05:58 ago) – Posting: # 20263
Views: 6,416

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
22,957 posts in 4,819 threads, 1,636 registered users;
85 visitors (0 registered, 85 guests [including 14 identified bots]).
Forum time: 20:03 CET (Europe/Vienna)

Nothing shows a lack of mathematical education more
than an overly precise calculation.    Carl Friedrich Gauß

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