[Rd] Time to revisit ifelse ?
Mikael Jagan
j@g@nmn2 @end|ng |rom gm@||@com
Fri Jul 11 10:41:13 CEST 2025
I don't mind putting together a minimal package with some prototypes, tests,
comparisons, etc. But perhaps we should aim for consensus on a few issues
beforehand. (Sorry if these have been discussed to death already elsewhere.
In that case, links to relevant threads would be helpful ...)
1. Should the type and class attribute of the return value be exactly the
type and class attribute of c(yes[0L], no[0L]), independent of 'test'?
Or something else?
2. What should be the attributes of the return value (other than 'class')?
base::ifelse keeps attributes(test) if 'test' is atomic, which seems
like desirable behaviour, though dplyr and data.table seem to think
otherwise:
> x <- diag(TRUE, 4L)
> base::ifelse(x, 1, -1)
[,1] [,2] [,3] [,4]
[1,] 1 -1 -1 -1
[2,] -1 1 -1 -1
[3,] -1 -1 1 -1
[4,] -1 -1 -1 1
> dplyr::if_else(x, 1, -1)
Error in if (n_processed == n_conditions && any(are_unused)) { :
missing value where TRUE/FALSE needed
> data.table::fifelse(x, 1, -1)
[1] 1 -1 -1 -1 -1 1 -1 -1 -1 -1 1 -1 -1 -1 -1 1
3. Should the new function be stricter and/or more verbose? E.g., should
it signal a condition if length(yes) or length(no) is not equal to 1
nor length(test)?
4. Should the most common case, in which neither 'yes' nor 'no' has a
'class' attribute, be handled in C? The remaining cases might rely on
method dispatch and thus require a separate "generic" implementation in
R. How much faster/more efficient would the C implementation have to
be to justify the cost (more maintenance for R-core, more obfuscation
for the average user)?
FWIW, my first (and untested) approximation of an ifelse2 is just this:
function (test, yes, no)
{
if (is.atomic(test)) {
if (!is.logical(test))
storage.mode(test) <- "logical"
}
else test <- if (isS4(test)) methods::as(test, "logical") else
as.logical(test)
nt <- length(test)
if (nt == 1L) {
ans <-
if (is.na(test))
c(yes[0L], no[0L])[1L]
else if (test)
c(yes[1L], no[0L])
else c(yes[0L], no[1L])
} else {
ans <- rep(c(yes[0L], no[0L]), length.out = nt)
ny <- length(yes)
nn <- length( no)
jy <- which( test)
jn <- which(!test)
if (length(jy))
ans[jy] <- if (ny == 1L) yes else if (ny >= nt) yes[jy] else
rep(yes, length.out = nt)[jy]
if (length(jn))
ans[jn] <- if (nn == 1L) no else if (nn >= nt) no[jn] else
rep( no, length.out = nt)[jn]
}
at <- attributes(test)
if (!is.null(at)) {
at[["class"]] <- oldClass(ans)
attributes(ans) <- at
}
ans
}
Mikael
> Date: Wed, 9 Jul 2025 12:06:49 +0200
> From: Martin Maechler <maechler using stat.math.ethz.ch>
>
>>>>>> Mikko Marttila via R-devel
>>>>>> on Wed, 09 Jul 2025 09:02:38 +0000 writes:
>
> > Thanks Antoine for starting this discussion. It would indeed be great to see
> > an improved `ifelse()` in base R.
>
> > I also agree with Duncan's suggestion that the way to proceed would be to
> > create a package where the improved version could be drafted, discussed and
> > refined so that R Core would have a concrete proposal to consider in the end.
>
> > Some initial thoughts on what should be considered:
>
> > Performance has been mentioned a few times. While it would of course be nice
> > to see improvements there I think the main goal is in the API. The goal for
> > performance should rather be that it doesn't deteriorate unacceptably.
>
> > While data.table's and dplyr's ifelse variants may serve as a good starting
> > point for identifiying the improvements needed, I don't think either is a good
> > candidate for simply copying as the base R candidate. A function in base R
> > should adhere to the conventions in base R; neither of the packages does that.
> > They instead have their own stricter requirements. For example:
>
> > * Incompatible lengths: Base R recycles with a warning, both packages error out.
> > * Different classes: Base R coerces loosely, dplyr uses stricter coercion rules
> > based on vctrs, and data.table doesn't allow any coercion.
>
> > Another point to consider is the handling of attributes for the result.
> > data.table copies from the first non-NA input from left to right, while dplyr
> > delegates to vctrs again for merging the attributes gracefully. This matters
> > for example for factors, where data.table special-cases them to require the
> > same levels, wherease dplyr merges them. For a base R solution, it would make
> > sense to delegate the attribute handling to `c()` somehow, as that's conceptually
> > what should be happening; we're combining values from the `yes` and `no` objects.
>
> > I'm sure there are many other points to consider, but as I said this is what
> > comes to mind at first. Best of luck with the effort.
>
> > Kind regards,
>
> > Mikko
>
> [..........]
>
> >> -----Original Message-----
> >> From: R-devel r-devel-bounces using r-project.org On Behalf Of Duncan Murdoch
> >> Sent: Tuesday, July 8, 2025 3:06 PM
> >> To: Josiah Parry josiah.parry using gmail.com; Avraham Adler avraham.adler using gmail.com
> >> Cc: r-devel using r-project.org
> >> Subject: Re: [Rd] Time to revisit ifelse ?
> >>
> >> Since you and Antoine are volunteering to do the work, why not start in
> >> the way I suggested? Write up a comparison of the known ifelse
> >> implementations, and either pick the best one, or choose the best parts
> >> of each. Put the result in a package containing nothing else, and
> >> invite comment from the wider community.
> >>
> >> My only comment in advance is that the package should have no
> >> dependencies other than base packages, for two reasons:
> >>
> >> 1. The hope is to have it adopted in base R, and for that it can't have
> >> any other dependencies.
> >>
> >> 2. If it's never adopted by R Core, I might still want to use it, but I
> >> don't want to add extra dependencies for just one little function.
> >>
> >> Duncan Murdoch
>
> [................]
>
> Thank you, Mikko, Antoine, Duncan, etc
> I'm trying to summarize the things I agree / or find important.
> Note that we had ifelse() discussions in the past (on this
> mailing list and/or possibly on R-help); I did get involved and
> spent many hours on coding myself, with no convincing result
> IIRC, but I do vaguely remember I got very convinced we should
> *not* plan to replace ifelse() but add a second version, say
> if.else() (as "if_else" is already taken by dplyr).
>
> 1) Antoine Fabri proposed that base R should get *another*
> version of ifelse() *in addition* to ifelse(). The issue
> hence is *NOT* replacing ifelse() by something incompatible.
>
> 2) Duncan Murdoch's points are *very* much to the point, most
> importantly:
>
> Propose (with discussion / RFC / ...) a function in a (single
> function) package which only depends on R's base package.
>
> I'd add to that that you should probably use the GPL-2 licence
> or are willing to donate it with that licence to R and do say so;
> e.g., we cannot add MIT-licenced things to R.
>
> 3) Ben Bolker's offer to "host" such a function in his 'gtools'
> package (w/ 0-dependency) would also be acceptable to me,
> even though it is against DM's "2. If it's never adopted by R Core, .."
>
> Best,
> Martin
>
> --
> Martin Maechler
> ETH Zurich and R Core team
>
More information about the R-devel
mailing list