HenrikBengtsson / Wishlist-for-R

Features and tweaks to R that I and others would love to see - feel free to add yours!
https://github.com/HenrikBengtsson/Wishlist-for-R/issues
GNU Lesser General Public License v3.0
133 stars 4 forks source link

Logical infix operator for possibly NULL objects #120

Closed wlandau closed 3 months ago

wlandau commented 3 years ago

Some packages define an internal %||% operator to make a decision based on whether an object is NULL. I find this helps make code more compact and readable.

`%||%` <- function(x, y) {
  if (is.null(x)) {
    y
  } else {
    x
  }
}

I personally also use %|||% and %||NA, but maybe that's a bit much.

`%|||%` <- function(x, y) {
  if (!length(x)) {
    y
  } else {
    x
  }
}

`%||NA%` <- function(x, y) {
  if (anyNA(x)) {
    y
  } else {
    x
  }
}
gmbecker commented 3 years ago

depending on the purpose, though, %||% could also reasonably be defined as what you're calling %|||%.

Also, and more importantly, there are some gotchas here. Big, sharp-edged ones, regarding operator precedence:

lobstr::ast(x=a %||% b & c)

█─&

├─█─%||%

│ ├─a

│ └─b

└─c

On Wed, Feb 10, 2021 at 11:31 AM Will Landau notifications@github.com wrote:

Some packages define an internal %||% operator to make a decision based on whether an object is NULL. I find this helps make code more compact and readable.

%||% <- function(x, y) { if (is.null(x)) { y } else { x } }

I personally also use %|||% and %||NA, but maybe that's a bit much.

%|||% <- function(x, y) { if (!length(x)) { y } else { x } } %||NA% <- function(x, y) { if (anyNA(x)) { y } else { x } }

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/HenrikBengtsson/Wishlist-for-R/issues/120, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAG53MM4SGIZ5OO3XW4YMDDS6LNHRANCNFSM4XNRIZIQ .

HenrikBengtsson commented 11 months ago

I think you've been heard;

$ R --vanilla
R Under development (unstable) (2023-10-26 r85413) -- "Unsuffered Consequences"
...
> x <- NULL
> x %||% 42
[1] 42

Source: https://github.com/wch/r-source/commit/10df7eac991c297271e16c7a1888240196d540f2

HenrikBengtsson commented 3 months ago

Closing; %||% is available in R (>= 4.4.0).